- 键盘启动的时候, viewDidLoad()函数里加
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
func keyboardWillShow(aNotification: NSNotification) {
print("text view begin")
// 获取键盘高度
let userinfo: NSDictionary = aNotification.userInfo! as NSDictionary
let nsValue = userinfo.object(forKey: UIKeyboardFrameEndUserInfoKey)
let keyboardRec = (nsValue as AnyObject).cgRectValue
let height = keyboardRec?.size.height
self.keyHeight = Int(height!)
UIView.animate(withDuration: 0.5, animations: {
var frame = self.view.frame
frame.origin.y = -(CGFloat)(self.keyHeight)
self.view.frame = frame
}, completion: nil)
}
//键盘隐藏时恢复
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
UIView.animate(withDuration: 0.5, animations: {
var frame = self.view.frame
frame.origin.y = 0
self.view.frame = frame
}, completion: nil)
return true
}