Ios UITextField textColor在辞职FirstResponder后恢复

Ios UITextField textColor在辞职FirstResponder后恢复,ios,iphone,uitextfield,resignfirstresponder,Ios,Iphone,Uitextfield,Resignfirstresponder,我有一个UIButton控制UITextField的textColor,我发现当我在UITextField上调用resignFirstResponder时,当文本字段是FirstResponder时对textColor所做的任何更改都会丢失,颜色会恢复到becomeFirstResponder之前的状态。我正在寻找的行为是,当文本字段是第一响应者时,textColor应该保持为所选择的内容 以下是相关代码: - (void)viewDidLoad { [super viewDidLoad

我有一个UIButton控制UITextField的textColor,我发现当我在UITextField上调用resignFirstResponder时,当文本字段是FirstResponder时对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.text颜色变为红色(文本也变为@“红色”,尽管这不是必需的)
  • 轻触键盘返回至resignFirstResponder,tf.textColor恢复为黑色(文本保持为@“红色”)
  • 类似地,如果初始textColor为红色,textField将恢复为红色


    我创建了一个示例项目,其中只包含产生这种行为所需的功能(可用)。提前感谢。

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

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

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

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

    嗯。在发布之前,我自己用你的示例代码试过了,效果很好。是的,确实有效。我必须检查一下为什么我在实际的更大项目中的最初尝试没有成功。非常感谢您的帮助。在我更大的项目中,有一个场景,当firstResponder被传递到另一个文本字段时,会调用resignFirstResponder,因此键盘永远不会被关闭,TextField应该返回:delegate方法永远不会被调用。相反,使用textfielddidediting:就可以了。也许这是更普遍的解决办法。感谢上帝!我的文本字段不知从哪里开始这样做,我不知道,也不知道为什么。不过这已经解决了,谢谢!