【发布时间】:2014-04-08 02:09:17
【问题描述】:
我想知道是否有办法让 UITextField 清除按钮“始终可见”
textfield.clearButtonMode = UITextFieldViewModeAlways;
似乎不起作用 .. 是否可以使用按钮关闭键盘?
提前致谢。
【问题讨论】:
标签: iphone uitextfield
我想知道是否有办法让 UITextField 清除按钮“始终可见”
textfield.clearButtonMode = UITextFieldViewModeAlways;
似乎不起作用 .. 是否可以使用按钮关闭键盘?
提前致谢。
【问题讨论】:
标签: iphone uitextfield
如前所述,苹果似乎在您清除字段后设置文本字段焦点。
解决方案非常简单。自己清场,resignFirstResponder 并返回 NO
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
textField.text = @"";
[textField resignFirstResponder];
return NO;
}
【讨论】:
[textField resignFirstResponder];。
在您的委托中,函数
- (BOOL)textFieldShouldClear:(UITextField *)textField
在用户想要清除文本字段时调用。如果你返回 YES 并调用
[textField resignFirstResponder];
键盘应该消失。我不知道 clearButtonMode,除了你可能想提前设置它,最好是在将视图添加到其父视图之前。
edit 为确保您确实让响应者辞职,请稍后再尝试:
[textField performSelector:@selector(resignFirstResponder) withObject:nil afterDelay:0.1];
【讨论】:
延迟对我来说效果不佳。相反,我向委托添加了一个实例变量:
BOOL cancelEdit;
然后在委托实现中:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (cancelEdit) {
cancelEdit = NO;
return NO;
} else {
return YES;
}
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
cancelEdit = YES;
return YES;
}
【讨论】:
UITextFieldDelegate textFieldShouldClear
- (BOOL)textFieldShouldClear:(UITextField *)textField {
[textField] resignFirstResponder];
return YES;
【讨论】:
我发现这种奇怪的行为是由一个竞争的手势识别器引起的,该手势识别器在调用 textFieldShouldClear: 之前退出了键盘之前的第一响应者。它似乎正在破坏第一响应者。
如果您采用这种方式进行设置,请确保您的手势识别器上的 cancelsTouchesInView 设置为 YES。这样你就不需要在 textFieldShouldClear: 或 textFieldShouldBeginEditing: 委托方法中做任何特殊的事情了。
【讨论】: