用到的变量
@IBOutlet weak var textView: UITextView!
var textViewHeight: CGFloat!
viewDidLoad
textViewHeight = textView.frame.origin.y
NotificationCenter.default.addObserver(self,selector: #selector(handleKeyboardDisShow(notification:)),name: NSNotification.Name.UIKeyboardDidShow,object: nil)
handleKeyboardDisShow
func handleKeyboardDisShow(notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
let value = userInfo.object(forKey: UIKeyboardFrameEndUserInfoKey)
let keyboardRec = (value as AnyObject).cgRectValue
let height = keyboardRec?.size.height
UITextView.animate(withDuration: 0.1,animations: {
var frame = self.textView.frame
frame.origin.y = height!
self.textView.frame = frame
})
}
textFieldShouldReturn
//MARK: 输入框enter回车事件
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
//让textView bottom位置还原
UITextView.animate(withDuration: 0.1,animations: {
var frame = self.textView.frame
frame.origin.y = self.textViewHeight
self.textView.frame = frame
})
return true
}
注销监听
deinit {
NotificationCenter.default.removeObserver(self)
}