我有一个控制 UITextField 的 textColor 的 UIButton,我发现当我在 UITextField 上调用 resignFirstResponder 时,当文本字段是第一响应者时对 textColor 所做的任何更改都将丢失,并且颜色恢复为becomeFirstResponder 之前的状态。我正在寻找的行为是当文本字段是第一响应者时,textColor 应该保留为所选的任何内容。
相关代码如下:
- (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;
}
更具体地说,行为是由以下操作产生的:
- UITextField *tf 最初是黑色的。
- 点击 tf 成为第一响应者。
- 点击 UIButton *b,tf.textColor 变为红色(文本也变为@"red",尽管这不是必需的)。
- 点击键盘返回 resignFirstResponder,tf.textColor 恢复为黑色(文本保持为@"red")。
类似地,如果初始 textColor 为红色,textField 将恢复为红色。
我创建了一个示例项目,其中仅包含产生此行为所需的功能(可用 here)。提前致谢。
最佳答案
作为解决方法,您可以在按下按钮时将所选颜色存储在属性上,然后执行以下操作:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
textField.textColor = self.selectedColor;
return YES;
}
更新
如评论中所述,放置此解决方法的更好位置似乎是在 textFieldDidEndEditing
中,因为它处理在字段之间跳转的情况:
- (void)textFieldDidEndEditing:(UITextField *)textField {
textField.textColor = self.selectedColor;
}
关于ios - UITextField textColor 在 resignFirstResponder 后恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285492/