更改所选TextField的背景颜色

时间:2014-10-01 09:55:06

标签: ios iphone

我正在创建一个我已经使用过用户注册的应用程序。在注册页面中,我创建了许多UITextField。我希望当用户选择任何TextField时,它的背景图像会发生变化。我使用代码来做到这一点:

- (IBAction)touchBegin:(id)sender
{
     //UILabel *opt = (UILabel *)[cell viewWithTag:101];
    if (_text1.isSelected) {
         _text1.background = [UIImage imageNamed:@"big_star_non_rating.png"];
    }
    else if (_text2.isSelected){
        _text2.background = [UIImage imageNamed:@"big_star_non_rating.png"];
    }
    else if (_text3.isSelected){
        _text3.background = [UIImage imageNamed:@"big_star_non_rating.png"];
    }
    else if (_text4.isSelected){
        _text4.background = [UIImage imageNamed:@"big_star_non_rating.png"];
    }
    else{

    }
}

但我根据自己的需要得不到结果。 我应该用什么来获得正确的输出?

2 个答案:

答案 0 :(得分:1)

确定您的文本域边框样式是否为UITextBorderStyleNone。

yourTextField.borderStyle = UITextBorderStyleNone;

yourTextField.background = [UIImage imageNamed:@"image.png"];

答案 1 :(得分:0)

我认为使用像这样的UITextFieldDelegate方法会更好更容易,例如:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    textField.background = [UIImage imageNamed:@"big_star_non_rating"];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    textField.background = [UIImage imageNamed:@"AnImageForNormalStateOrSetNilBackground"];
    return YES;
}

希望它有所帮助。

相关问题