[英]Toolbar above keyboard doesn't hide when keyboard hides
我在鍵盤上方添加了一個工具欄,以顯示完成按鈕以關閉鍵盤。 我已經在我的登錄屏幕上添加了它。 當鍵盤顯示並且我點擊保存密碼圖標到 select 保存密碼時,鍵盤隱藏但工具欄沒有隱藏。 工具欄位於屏幕底部,然后在鍵盤再次顯示時隨鍵盤向上移動。 看起來很糟糕。
如何修復它以使工具欄不會自行顯示並且僅使用鍵盤顯示/隱藏?
override func viewDidLoad() {
super.viewDidLoad()
self.emailTextField.addDoneButton(title: "Done", target: self, selector: #selector(tapDone(sender:)))
self.passwordTextField.addDoneButton(title: "Done", target: self, selector: #selector(tapDone(sender:)))
}
@objc func tapDone(sender: Any) {
self.view.endEditing(true)
}
extension UITextField {
// Add done button above keyboard
func addDoneButton(title: String, target: Any, selector: Selector) {
let toolBar = UIToolbar(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 44.0)))
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let barButton = UIBarButtonItem(title: title, style: .plain, target: target, action: selector)
barButton.setTitleTextAttributes([NSAttributedString.Key.font : UIFont.main, NSAttributedString.Key.foregroundColor : UIColor.red], for: [])
toolBar.setItems([flexible, barButton], animated: false)
self.inputAccessoryView = toolBar
}
}
我個人以不同的方式處理這個問題,因為我沒有使用任何工具欄,而是使用鍵盤上方的自定義視圖。 由於我希望這些視圖根據鍵盤 position 進行動畫處理和出現/消失,因此我首先聽鍵盤更改:
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardChanged(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
然后在此處手動處理鍵盤當前大小和 position,如下所示:
func keyboardChanged(_ userInfo: Dictionary<AnyHashable, Any>?) {
if let userInfo = userInfo {
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
// keyboard is masked, you can mask/move your toolbar here
} else {
// update your toolbar visibility and/or position/constraints here using 'endFrame?.size.height'
}
// animate your toolbar or any other view here:
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: {
// animate what you need here
self.view.layoutIfNeeded()
},
completion: nil)
}
}
因此,在您的情況下,我將首先創建工具欄並將其限制在屏幕底部。 然后我會使用上面的代碼來處理它的 position 和可見性。
然后,每當鍵盤 position 更新時,您就可以在上面顯示的鍵盤通知處理程序中處理工具欄(位置和可見性)。
可能不是這個問題的直接答案,但我強烈建議您查看 IQKeyboardManager 庫。 默認情況下,它是一個單行鍵盤處理程序,但您可以輕松添加附件視圖,並且可以很好地管理它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.