【发布时间】:2017-08-22 09:32:03
【问题描述】:
我有一个固定在顶部、底部、尾随和前导的全屏 UITableView。此 ViewController 位于导航控制器内。我希望表格的底部向上移动并使用键盘进行动画处理。我有以下代码:
// MARK: Keyboard
func registerObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func unregisterObservers() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(_ notification: Notification) {
let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardAnimationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
let keyboardAnimationCurve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
tableViewBottomConstraint.constant = keyboardFrame.height
UIView.animate(withDuration: TimeInterval(keyboardAnimationDuration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(keyboardAnimationCurve))], animations: {
self.view.layoutIfNeeded()
}, completion: { (finished: Bool) in
})
}
func keyboardWillHide(_ notification: Notification) {
let keyboardAnimationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
let keyboardAnimationCurve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
tableViewBottomConstraint.constant = 0
UIView.animate(withDuration: TimeInterval(keyboardAnimationDuration), delay: 0, options: [UIViewAnimationOptions(rawValue: UInt(keyboardAnimationCurve))], animations: {
self.view.layoutIfNeeded()
}, completion: { (finished: Bool) in
})
}
我在 ViewDidLoad 上注册了观察者。当键盘出现时,动画看起来很生涩。然而,解雇动画似乎没有任何问题。我在这里做错了什么?我是否设置了动画时长或曲线错误?
【问题讨论】:
-
如果你使用 UITableViewController 而不是 UIViewController,它会自动工作
-
与其上移tableView约束,考虑上移tableView的contentOffset,会好很多
-
@Tj3n 我试过了,但动画还是生涩
-
不应该,尝试将它们包装在主线程调度中
标签: ios swift uitableview