简体   繁体   中英

Change the background color of selected TextField

I am creating an app in which I have used user registration.In registration page, I have created many UITextFields.I wants that when a user select any TextField then its background Image is change. I uses the code to do that is:

- (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{

    }
}

But I am not getting the result according to my need. What should I use to get correct output?

be sure whether your textfield border style is UITextBorderStyleNone.

yourTextField.borderStyle = UITextBorderStyleNone;

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

I think that it's better and easier to use UITextFieldDelegate methods like this, for example:

- (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;
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM