1.先注册对键盘的监听:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide", name: UIKeyboardWillHideNotification, object: nil)
2.实现两个Selector:
@objc private func keyboardWillShow(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame = info[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
let responderTextField = textFields.filter({ $0.isFirstResponder() }).first!
let distanceToKeyboard = keyboardFrame.origin.y - CGRectGetMaxY(responderTextField.convertRect(responderTextField.frame, toView: view))
if distanceToKeyboard < 0 {
view.frame.origin.y -= -distanceToKeyboard
}
}
@objc private func keyboardWillHide() {
view.frame.origin.y = 0
}
但不知道为什么不需要加UIView.animateWithDuration就有了动画呢?
3.记得要移除监听哦:
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
NSLog("LoginViewController deinits")
}
网友评论