【发布时间】:2018-02-03 02:02:27
【问题描述】:
我正在尝试复制 whatsapp、imessage 等键盘,发送按钮/文本字段位于其顶部 我有一个 TableView 和一个包含文本字段和发送按钮的容器视图。
每次我点击文本字段时,容器视图都会上升并“坐在”键盘上,但是一旦我开始输入,容器视图就会消失并进入最初的底部。为什么会这样??
override func viewDidLoad() {
messageTextfield.delegate=self
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}
@objc func keyboardWillShow(_ sender: Notification) {
let duration = sender.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = sender.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
let beginningFrame = (sender.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let endFrame = (sender.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = endFrame.origin.y - beginningFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.containerView.frame.origin.y += deltaY
}, completion: nil)
}
@objc func keyboardWillHide(_ sender: Notification) {
let userInfo: [AnyHashable: Any] = sender.userInfo!
let keyboardSize: CGSize = (userInfo[UIKeyboardFrameBeginUserInfoKey]! as AnyObject).cgRectValue.size
self.containerView.frame.origin.y += keyboardSize.height
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
super.touchesBegan(touches, with: event)
view.endEditing(true)
}
【问题讨论】: