[英]UITextField textColor reverts after 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;
}
更具體地說,該行為由以下操作產生:
類似地,如果初始textColor為紅色,則textField將恢復為紅色。
我創建了一個示例項目,其中只包含產生此行為所需的功能( 此處提供 )。 提前致謝。
作為解決方法,您可以在按下按鈕時將所選顏色存儲在屬性上並執行以下操作:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
textField.textColor = self.selectedColor;
return YES;
}
UPDATE
正如評論中所指出的,放置此變通方法的更好地方似乎是在textFieldDidEndEditing
因為它處理了字段間跳轉的情況:
- (void)textFieldDidEndEditing:(UITextField *)textField {
textField.textColor = self.selectedColor;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.