如何调整滚动视图以垂直补偿键盘?请阅读...如何在swift 3+中调整键盘的滚动视图
是的我知道这是一些基本的信息,但我今天随机发现,我看到关于这个主题的所有答案都遍布整个地方与信息,版本和/或使用刘海遍布地方......但对于Swift 3+来说没有什么可靠的。
如何调整滚动视图以垂直补偿键盘?请阅读...如何在swift 3+中调整键盘的滚动视图
是的我知道这是一些基本的信息,但我今天随机发现,我看到关于这个主题的所有答案都遍布整个地方与信息,版本和/或使用刘海遍布地方......但对于Swift 3+来说没有什么可靠的。
斯威夫特3:
let scrollView = UIScrollView()
添加观察员。
override open func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(noti:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(noti:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
添加一些功能,以监听通知:
//---------------------------------
// MARK: - Notification Center
//---------------------------------
func keyboardWillHide(noti: Notification) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
func keyboardWillShow(noti: Notification) {
guard let userInfo = noti.userInfo else { return }
guard var keyboardFrame: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else { return }
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
scrollView.contentInset = contentInset
}
值得注意的是,如果你的部署目标是iOS的9或更高版本,您不需要再删除观察者。查看NotificationCenter文档以获取更多信息。
deinit {
NotificationCenter.default.removeObserver(self)
}
的修改,使其在iOS上11的工作是使用UIKeyboardFrameEndUserInfoKey
而非UIKeyboardFrameBeginUserInfoKey
。只需简单的方法来解答@satshshin的解决方案:
@objc func keyboardWillShow(_ notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
scrollView.contentInset.bottom = keyboardSize.height
}
}
@objc func keyboardWillHide(_ notification: NSNotification) {
scrollView.contentInset.bottom = 0
}