在我的项目中,我有几个包含许多 UITextField 的页面。所以我认为最好创建一个名为 hideKeyboard 的实用方法,它在任何情况下都可以使用。 这是我的解决方案,但实际上这段代码中有些地方感觉不对。 对此有更好的解决方案吗?
+(void) hideKeyBoard {
UITextField* t = [[UITextField alloc] initWithFrame:CGRectNull];
[[UIApplication sharedApplication].keyWindow addSubview:t];
[t becomeFirstResponder];
[t resignFirstResponder];
[t removeFromSuperview];
}
最佳答案
一个非常简单的解决方案是使用响应链,如前所述 here
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
to:nil
from:nil
forEvent:nil];
通过将操作发送到 nil
,它会被发送到响应链中,当然第一个有机会响应的对象是 firstResponder
旁注 我看到这篇文章的唯一原因是因为每周时事通讯iOSDevWeekly , 这绝对值得订阅
编辑
我猜想用蛮力的方式来做这件事
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
关于iphone - 隐藏键盘的实用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11879745/