iOS 11引入的新的安全区域布局指南非常适用于防止内容显示在栏下,但它不包括键盘。这意味着当键盘显示时,内容仍然隐藏在其后面,这是我要解决的问题。
我的方法是基于监听键盘通知,然后通过additionalSafeAreaInsets
调整安全区域。
以下是我的代码:
override func viewDidLoad() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
//MARK: - Keyboard
extension MyViewController {
@objc func keyboardWillShow(notification: NSNotification) {
let userInfo = notification.userInfo!
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded();
}
}
@objc func keyboardWillHide(notification: NSNotification) {
additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded();
}
}
@objc func keyboardWillChange(notification: NSNotification) {
let userInfo = notification.userInfo!
let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded();
}
}
}
这个方法很有效,因为MyController
是一个 UIViewController
,有一个 UITableView
沿着整个安全区域延伸。现在当键盘出现时,底部会被推上去,以便没有单元格位于键盘后面。
问题是底部栏的位置。我在底部也有一个工具栏,已包含在安全区域内。因此,将完整键盘高度设置为额外的安全区域插入会将表视图的底部过多地向上推动,正好等于底部栏的高度。要使此方法有效,必须将 additionalSafeAreaInsets.bottom
设置为键盘高度减去底部栏的高度。
问题1:获取当前底部安全区域间隙的最佳方法是什么?手动获取工具条的框架并使用其高度?还是直接从安全区域布局指南中获取间隙?
问题2:可以假定底部栏可以改变大小而不影响键盘的大小,因此我也应该实现某种监听栏框架更改的方法。最好在 viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
中完成吗?或其他地方?
谢谢