Swift 3 NSNotificationCenter键盘将显示/隐藏

我有一段代码在Swift 2中工作,我试图使用xCode更新代码到最新的版本,我修复了一切,除了两个问题

我有这个代码

let loginvc : LoginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC NotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) 

与此一起配对

 func keyboardWillShow(notification: NSNotification) { constraint.constant = -100 UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } } func keyboardWillHide(notification: NSNotification) { constraint.constant = 25 UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() } } 

在第一部分,我现在得到一个错误,说“types'LoginViewController'没有成员'keyboardwillshow / hide'

我不明白为什么它没有看到下面的方法

有没有人知道这个问题的解决scheme?

查看更新的Swift编程语言手册 。 页1027和1028是你在找什么。 它应该是这样的:

 func keyboardWillHide(_ notification: NSNotification) {… 

注意上面的附加下划线。 也:

 #selector(LoginViewController.keyboardWillHide(_:)) 

您还可能需要将@objc(keyboardWillHideWithNotification:)添加到您的class级。

使用那个在swift3上工作的代码

你可以使用你的ViewController(例如loginvc )来添加通知

 let loginvc : LoginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC NotificationCenter.default.addObserver(self, selector: #selector(loginvc.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(loginvc.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 

然后添加键盘隐藏和显示方法

 func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { print("Show") } } func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { print("Hide") } } 

获取显示键盘NSNotificationCenter有一些变化:

 NotificationCenter.default.addObserver(self, selector: #selector(NovaVisitaVC.abreTeclado(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(NovaVisitaVC.abreTeclado(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)