【发布时间】:2011-11-04 02:20:35
【问题描述】:
在使用我的应用程序期间收到短信时,我希望关闭所有打开的键盘。如何从我的应用委托中的 applicationWillResignActive 执行此操作?
【问题讨论】:
标签: objective-c ios uiapplicationdelegate
在使用我的应用程序期间收到短信时,我希望关闭所有打开的键盘。如何从我的应用委托中的 applicationWillResignActive 执行此操作?
【问题讨论】:
标签: objective-c ios uiapplicationdelegate
像answer 中的示例那样实现代码。让您的视图控制器注册UIApplicationWillResignActiveNotification。当通知触发时,请致电resignFirstResponder。这样可以避免 UIApplicationDelegate 和视图控制器之间的紧密耦合。假设您的视图控制器有一个名为 textField 的 UITextField:
- (void) applicationWillResign {
[self.textField resignFirstResponder];
}
- (void) viewDidLoad {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationWillResign)
name:UIApplicationWillResignActiveNotification
object:NULL];
}
【讨论】:
对于 Swift 5 实现,试试这个
override func viewDidLoad() {
super.viewDidLoad()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
}
@objc func appMovedToBackground() {
print("App moved to background!")
}
【讨论】: