ios - UITextField textColor 在 resignFirstResponder 后恢复

标签 ios iphone uitextfield resignfirstresponder

我有一个控制 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;
}

更具体地说,行为是由以下操作产生的:

  1. UITextField *tf 最初是黑色的。
  2. 点击 tf 成为第一响应者。
  3. 点击 UIButton *b,tf.textColor 变为红色(文本也变为@"red",尽管这不是必需的)。
  4. 点击键盘返回 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/

相关文章:

iphone - UIViewController 编辑按钮状态始终相同

ios - 在 iOS swift 中使用 datePicker 处理多个文本字段

ios - 如果 textField 为空,Swift 会给出特定的文本

ios - 将文件添加到 Xcode 和 git

ios - 更改我的 NSString 中特定字符的字体系列

ios - Realm.io 可选属性

ios - 将图像从一个 UIViewController 发送到另一个 UIViewController

ios - SCNParticleSystem 从文档目录加载

iphone - 强制文本垂直放置在 UILabel 中?

Swift UITextField 目标 Action 作为闭包,不删除目标 Action 的问题