设置一个全局变量:
var keyBoardNeedLayout: Bool = true
在viewDidLoad()中注册通知中心:
override func viewDidLoad() {
super.viewDidLoad()
// 注册通知中心,监听键盘弹起的状态
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillShow(_:)),name: .UIKeyboardWillShow, object: nil)
// 注册通知中心,监听键盘回落的状态
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillHide(_:)),name: .UIKeyboardWillHide, object: nil)
}
键盘弹出的响应方法:
func keyboardWillShow(_ notification: NSNotification) {
print("show")
if let userInfo = notification.userInfo,
let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {
let frame = value.cgRectValue
let intersection = frame.intersection(self.view.frame)
let deltaY = intersection.height
if keyBoardNeedLayout {
UIView.animate(withDuration: duration, delay: 0.0,
options: UIViewAnimationOptions(rawValue: curve),
animations: { _ in
self.view.frame = CGRect(x:0, y: -deltaY, width: self.view.bounds.width, height: self.view.bounds.height)
self.keyBoardNeedLayout = false
self.view.layoutIfNeeded()
}, completion: nil)
}
}
}
func keyboardWillHide(_ notification: NSNotification) {
print("hide")
if let userInfo = notification.userInfo,
let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {
let frame = value.cgRectValue
let intersection = frame.intersection(self.view.frame)
let deltaY = intersection.height
UIView.animate(withDuration: duration, delay: 0.0,
options: UIViewAnimationOptions(rawValue: curve),
animations: { _ in
self.view.frame = CGRect(x:0, y: deltaY, width: self.view.bounds.width, height: self.view.bounds.height)
self.keyBoardNeedLayout = true
self.view.layoutIfNeeded()
}, completion: nil)
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}