我正在为练习创建扩展名,只需简单地调用它即可,它可以在键盘抬起时控制视图高度,并在将来使事情变得更容易。
这是屏幕截图: (我在控制器父视图中创建了一个scrollView,因此当键盘向上时,用户可以滚动整个页面)
问题:
1-键盘高度有时是错误的,具体取决于我如何连接scrollView底部约束。
2-有时应该给scrollView底部约束一个负值,以使scrollView变小,有时它需要一个正值!它也取决于您如何将scrollView底部约束与其superView连接起来(这就是我创建“ isReverse”变量的原因)。
这是我的扩展名:
extension UIViewController {
func watchKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc private func keyboardWillShow(notification: NSNotification) {
let isReverse = true // in some case you should turn this boolean to false to get the proper result.
if tabBarController != nil {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if let bottomConstraint = view.constraints.filter({ $0.firstAttribute == .bottom }).first {
UIView.animate(withDuration: 0.4) {
if isReverse {
bottomConstraint.constant = -keyboardSize.height + self.tabBarController!.tabBar.frame.size.height
} else {
bottomConstraint.constant = keyboardSize.height - self.tabBarController!.tabBar.frame.size.height
}
self.view.layoutIfNeeded()
}
}
}
} else {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let isReverse = true // in some case you should turn this boolean to false to get the proper result.
if let bottomConstraint = view.constraints.filter({ $0.firstAttribute == .bottom }).first {
UIView.animate(withDuration: 0.4) {
bottomConstraint.constant = isReverse ? -keyboardSize.height : keyboardSize.height
self.view.layoutIfNeeded()
}
}
}
}
}
@objc private func keyboardWillHide(notification: NSNotification) {
if let bottomConstraint = view.constraints.filter({ $0.firstAttribute == .bottom }).first {
UIView.animate(withDuration: 0.4) {
bottomConstraint.constant = 0
self.view.layoutIfNeeded()
}
}
}
}
预先感谢...