<aside> 💡 使UITextField在使用者輸入時鍵盤不會擋住編輯地區
</aside>
鍵盤return鍵
從textField自動彈出的鍵盤有return
可透過UITextFieldDelegate的textFieldShouldReturn收起鍵盤
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
點擊鍵盤外畫面
使用點擊判斷動作來收起鍵盤
在viewDidLoad建立點擊偵測UITapGestureRecognizer
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
self.view.addGestureRecognizer(tap)
selector的method
@objc func dismissKeyboard() {
self.view.endEditing(true)
}
針對鍵盤動作的NotificationCenter
UIResponder.keyboardWillShowNotification(鍵盤即將顯示)
UIResponder.keyboardWillHideNotification(鍵盤即將消失)
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
取得Notification userInfo property
UIResponder.keyboardFrameEndUserInfoKey(在鍵盤動畫結束後取的其frame)
利用contentInset設定scrollView所需的間距
<aside> 💡 由於keyboard是直接覆蓋在你的畫面上,所以我們透過增加scrollView的contentInset(並設定高度就是keyboard的height)來避開keyboard
</aside>
@objc func keyboardWasShown(_ notification: Notification) {
guard let info = notification.userInfo,
let keyboardFrameValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardFrame = keyboardFrameValue.cgRectValue
let keyboardSize = keyboardFrame.size
// set contentInset to add it on scrollView and match with keyboard height
// contentInset is an additional blank space you can use since keyboard is overlap on you view, you create contentInset to avoid overlapping
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
當keyboard要消失時,就將contentInset歸0
@objc func keyboardWillBeHidden(_ notification: Notification) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
https://github.com/KrauserHuang/ScrollingForm