Kex*_*Ari 2 uitableview ios swift
我有一个全屏 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
})
}
Run Code Online (Sandbox Code Playgroud)
我在 ViewDidLoad 上注册了观察者。当键盘出现时,动画看起来很生涩。然而,解雇动画似乎没有任何问题。我在这里做错了什么?我是否设置了动画持续时间或曲线错误?
小智 5
我通过执行以下操作来做到这一点:
为底部约束声明一个 IBOutlet 变量。请务必链接适当的约束,对于您的情况,这是 tableView 的底部约束。
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
Run Code Online (Sandbox Code Playgroud)
添加一个函数来处理调整。
func keyboardChangeFrame(_ notification: Notification) {
let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
bottomConstraint.constant = view.bounds.height - endFrame.origin.y
self.view.layoutIfNeeded()
}
Run Code Online (Sandbox Code Playgroud)
最后,在 viewDidLoad 添加 UIKeyboardWillChangeFrame 观察者。
NotificationCenter.default.addObserver(self
, selector: #selector(keyboardChangeFrame)
, name: NSNotification.Name.UIKeyboardWillChangeFrame
, object: nil)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |