我试图在键盘显示和消失时运行一个函数,并具有以下代码:
let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(ViewController.keyBoardUp(Notification :)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
以下功能keyBoardUp
:
func keyBoardUp( Notification: NSNotification){ print("HELLO") }
但是,当键盘显示时,该功能不会打印到控制台.非常感谢帮助
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil) } func keyboardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { print("notification: Keyboard will show") if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } func keyboardWillHide(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0 { self.view.frame.origin.y += keyboardSize.height } } }
@ vandana的答案已更新,以反映Swift 4.2中对本机通知的更改.
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { print("notification: Keyboard will show") if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0 { self.view.frame.origin.y += keyboardSize.height } } }
此外,您需要使用UIKeyboardFrameEndUserInfoKey
来考虑iOS 11safeAreaInset
引入的更改.
设置键盘通知观察器
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) }
并在您的函数中处理它
func keyboardNotification(notification: NSNotification) { print("keyboard displayed!!") }
希望这会帮助你.