在使用我的应用程序期间收到短信时,我希望任何打开的键盘都被驳回。我如何在app委托中从applicationWillResignActive中做到这一点?
实现这个答案中的示例代码。让你的视图控制器注册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!")
}
更多信息请访问https://www.hackingwithswift.com/example-code/system/how-to-detect-when-your-app-moves-to-the-background