6

我有一个控制 UITextField 的 textColor 的 UIButton,我发现当我在 UITextField 上调用 resignFirstResponder 时,在文本字段是第一响应者时对 textColor 所做的任何更改都会丢失,并且颜色会恢复到之前的状态成为第一响应者。我正在寻找的行为是 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 成为FirstResponder。
  3. 点击 UIButton *b,tf.textColor 变为红色(文本也变为@"red",尽管这不是必需的)。
  4. 点击键盘返回 resignFirstResponder,tf.textColor 恢复为黑色(文本保持为@“red”)。

类似地,如果初始 textColor 为红色,则 textField 恢复为红色。

我创建了一个示例项目,其中仅包含产生此行为所需的功能(可在此处获得)。提前致谢。

4

1 回答 1

7

作为一种解决方法,您可以在按下按钮时将所选颜色存储在属性上并执行以下操作:

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

更新

如评论中所述,放置此解决方法的更好位置似乎是,textFieldDidEndEditing因为它处理字段之间跳转的情况:

- (void)textFieldDidEndEditing:(UITextField *)textField {
    textField.textColor = self.selectedColor;
}
于 2014-03-09T17:53:28.087 回答