UITextField textColor returns after resignFirstResponder

I have a UIButton that controls the textColor of a UITextField, and I find that when I call resignFirstResponder on a UITextField, any changes to the textColor made while the text field is the first responder are lost and the color returns to before becoming the first by the respondent. The behavior I'm looking for is that textColor should remain as it was when the text field is the first responder.

Here is the relevant code:

- (void)viewDidLoad { [super viewDidLoad]; self.tf = [[UITextField alloc] initWithFrame:CGRectMake(0.0f, 120.0f, self.view.bounds.size.width, 70.0f)]; self.tf.delegate = self; self.tf.text = @"black"; self.tf.font = [UIFont fontWithName:@"AvenirNext-DemiBold" size:48.0f]; self.tf.textColor = [UIColor blackColor]; [self.view addSubview:self.tf]; self.tf.textAlignment = UITextAlignmentCenter; UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 220.0f, self.view.bounds.size.width, 20.0f)]; [b addTarget:self action:@selector(changeColor:) forControlEvents:UIControlEventTouchUpInside]; [b setTitle:@"Change color" forState:UIControlStateNormal]; [b setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal]; [self.view addSubview:b]; } - (void)changeColor:(UIButton *)button { if ([self.tf.textColor isEqual:[UIColor blackColor]]) { self.tf.text = @"red"; self.tf.textColor = [UIColor redColor]; } else { self.tf.text = @"black"; self.tf.textColor = [UIColor blackColor]; } } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } 

More specifically, the behavior is created using the following actions:

  • UITextField * tf is initially black.
  • Press tf to become FirstResponder.
  • Press UIButton * b, tf.textColor will change to red (the text also changes to @ "red", although this is optional).
  • Touch the keyboard. Return to resignFirstResponder, tf.textColor will return to black (text remains as @ "red").

Similarly, if the original textColor turns red, the textField returns to red.

I created a sample project with only the functions necessary to create this behavior (available here ). Thanks in advance.

+6
source share
1 answer

As a workaround, you can simply save the selected color in the property when you click the button and do this:

 - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; textField.textColor = self.selectedColor; return YES; } 

UPDATE

As noted in the comments, it is best to use this workaround in textFieldDidEndEditing , because it handles the case of a jump between fields:

 - (void)textFieldDidEndEditing:(UITextField *)textField { textField.textColor = self.selectedColor; } 
+7
source

All Articles