NSNotificationCenter Swift 3.0在键盘上显示和隐藏
我想在键盘显示和消失时运行一个函数,并具有以下代码:
let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(ViewController.keyBoardUp(Notification :)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
而下面的functionkeyBoardUp
:
func keyBoardUp( Notification: NSNotification){ print("HELLO") }
但是,键盘显示时,该function不会打印到控制台。 帮助将不胜感激
Swift 3:
重写func viewDidLoad(){
super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { print("HELLO") if self.view.frame.origin.y == 0{ self.view.frame.origin.y -= keyboardSize.height } } } func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0{ self.view.frame.origin.y += keyboardSize.height } } }
设置键盘通知观察者
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) }
并在你的function处理它
func keyboardNotification(notification: NSNotification) { print("keyboard displayed!!") }
希望这会帮助你。