我的目标只是在用户单击键盘上的完成按钮后将文本保存在 UITextField 上。我可以在 extFieldShouldReturn 或 textFieldDidEndEditing 中执行此操作:这有什么区别吗?还是有更好的方法?
谢谢!!
最佳答案
textFieldShouldReturn 只有在用户按下返回键时才会被调用。如果键盘由于某些其他原因(例如用户选择另一个字段或将 View 切换到另一个屏幕)而被取消,则不会,但 textFieldDidEndEditing 会。
最好的方法是使用 textFieldShouldReturn 来退出响应者(隐藏键盘),如下所示:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//hide the keyboard
[textField resignFirstResponder];
//return NO or YES, it doesn't matter
return YES;
}
当键盘关闭时,textFieldDidEndEditing 将被调用。然后,您可以使用 textFieldDidEndEditing 对文本执行某些操作:
- (BOOL)textFieldDidEndEditing:(UITextField *)textField
{
//do something with the text
}
但是如果您实际上只想在用户明确按下键盘上的“go”或“send”或“search”(或其他)按钮时执行操作,那么您应该将该处理程序放在 textFieldShouldReturn 方法中,像这样:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//hide the keyboard
[textField resignFirstResponder];
//submit my form
[self submitFormActionOrWhatever];
//return NO or YES, it doesn't matter
return YES;
}
关于ios - 保存 UITextField 测试的最佳方法 : textFieldShouldReturn or textFieldDidEndEditing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101542/