如何調整滾動視圖以垂直補償鍵盤?請閱讀...如何在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
}