从 AppDelegate.m 中的 applicationDidEnterBackground 中去掉键盘

Posted

技术标签:

【中文标题】从 AppDelegate.m 中的 applicationDidEnterBackground 中去掉键盘【英文标题】:Get rid of the keyboard from applicationDidEnterBackground in the AppDelegate.m 【发布时间】:2012-02-07 14:53:47 【问题描述】:

我的MainViewController.m 文件中有一个带有文本字段的应用程序。该文件中还有一个滚动视图,因此当键盘出现时,视图会滚动,以便用户可以看到文本字段。当用户点击屏幕时,键盘将被关闭。除了用户点击主页按钮将应用程序置于后台然后返回的情况外,一切都运行良好。在这种情况下,键盘仍然处于启动状态,但我的滚动视图处于关闭状态,并且隐藏了文本字段。理想情况下,我也希望关闭键盘。

经过调查,被调用的方法都在AppDelegate.m 文件中(不幸的是它没有进入 ViewDidLoad 或任何 View 生命周期方法)。如何从 AppDelegate.m 文件中的 applicationDidEnterBackground 关闭键盘? 我是一个新手——我尝试在我的 MainViewController 文件中创建一个 +dismisskeyboard 函数并从 Appdelegate 调用它,但是我的 Textfields 都是实例变量,这不起作用。我还尝试在我的 AppDelegate 文件中创建一个文本字段,然后执行此操作 -

[_someField becomeFirstResponder];

[_someField resignFirstResponder];

但这也不起作用...我不知道如何将故事板上的任何内容链接到 someField 的 AppDelegate 属性。

谁能提出解决这个问题的正确方法?

【问题讨论】:

【参考方案1】:

只需在您的 MainViewController 类中为 UIApplicationDidEnterBackgroundNotification 注册一个方法,然后在那里关闭您的键盘。例如 注册接收通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil];

然后添加这个方法

- (void) receivedNotification:(NSNotification *) notification

    [txtFld resignFirstResponder];

【讨论】:

谢谢!多么简单的解决方案!我仍在学习通知,但管理了这个,它运行良好。

以上是关于从 AppDelegate.m 中的 applicationDidEnterBackground 中去掉键盘的主要内容,如果未能解决你的问题,请参考以下文章

iOS AppDelegate.m:处理 openUrl RCTLinkingManager 和 Twitter - 方法 'application:openURL:options:' 的重复声明

从 AppDelegate.m 中的 applicationDidEnterBackground 中去掉键盘

如何将数据从 AppDelegate 传递到 ViewController?

如何从 AppDelegate.m 访问 tabBarController?

如何从 Xcode 中的 AppDelegate.m 文件更新 UILabel 的文本?

iOS AppDelegate的.m文件解析