gpt4 book ai didi

ios - 键盘隐藏时键盘上方的工具栏不会隐藏

转载 作者:行者123 更新时间:2023-12-01 15:37:56 26 4
gpt4 key购买 nike

我在键盘上方添加了一个工具栏以显示完成按钮以关闭键盘。我已经在我的登录屏幕上添加了它。当键盘显示并且我点击保存的密码图标以选择保存的密码时,键盘会隐藏但工具栏不会隐藏。工具栏位于屏幕底部,然后在键盘再次显示时随键盘一起向上移动。看起来很糟糕。
如何修复它以便工具栏不会自行显示而仅使用键盘显示/隐藏?

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
}
}

最佳答案

我个人以不同的方式处理这个问题,因为我没有使用任何工具栏,而是在键盘上方使用自定义 View 。由于我希望这些 View 根据键盘位置动画和出现/消失,我首先听键盘变化:

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardChanged(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
然后在此处手动处理键盘当前大小和位置,如下所示:
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)
}
}
因此,在您的情况下,我会先创建工具栏并将其限制在屏幕底部。然后我会使用上面的代码来处理它的位置和可见性。
然后,无论何时更新键盘位置,您都可以在上面显示的键盘通知处理程序中处理工具栏(位置和可见性)。

关于ios - 键盘隐藏时键盘上方的工具栏不会隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62520053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com