我有一个UISearchBar,单击它时会显示键盘。但是,如果用户在显示键盘的同时按下主页按钮,然后返回应用程序,则键盘仍然可见。当应用程序关闭/进入后台时,我如何隐藏键盘?
我在viewDidDisappear中尝试了以下操作:
[eventSearchBar resignFirstResponder];
[eventSearchBar endEditing:YES];
我也在appDidEnterBackground:中的代理中尝试过这一点
[self.rootController.navigationController.view endEditing:YES];
这些都不起作用。
您可以在appDelegate中执行此操作。。。。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[self.window endEditing:YES];
}
这个的Swift版本:
func applicationDidEnterBackground(application: UIApplication) {
window?.endEditing(true)
}
在视图控制器中,例如在init方法中,注册UIApplicationWillResignActiveNotification
:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(willResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
当应用程序进入后台时,使搜索显示控制器处于非活动状态。这将从搜索字段中删除焦点并隐藏键盘:
- (void)willResignActive:(NSNotification *)note
{
self.searchDisplayController.active = NO;
// Alternatively, if you only want to hide the keyboard:
// [self.searchDisplayController.searchBar resignFirstResponder];
}
不要忘记删除dealloc方法中的观测者:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationWillResignActiveNotification
object:nil];
swift 3.2版本中的解决方案
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(hideTextField), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func hideTextField(){
eventSearchBar.endEditing(true)
}
最好的方法是放置window?。endEditing(true)in applicationWillResignActive on AppDelegate:
func applicationWillResignActive(_ application: UIApplication) {
window?.endEditing(true)
}
我的所有标准方法都偶尔失败。到目前为止,这是我获得可靠结果的唯一途径。
在最上面的控制器中。
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willResignActiveNotification:) name:UIApplicationWillResignActiveNotification object:nil];
}
-(void) willResignActiveNotification:(NSNotification*) vNotification {
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
[self setEditing:NO];
}
有一种奇怪的情况,文本字段将不再响应resignFirstResponder
或endEditing
,但键盘仍在上。