@Wolverine 和@Bhavin Ramani 的回答非常棒:让您的自定义标题 保持领先的最佳方式是手动处理您的键盘(根据 IQKeyboardSwift 作者的comment)。如果您使用 iOS 默认导航栏,它似乎是由库为您处理的。
在这里我只想分享一些关于这个主题的更新,以供我将来参考,因为答案有点老了,而且一些 Swift 语法已经改变。下面的代码是用 Xcode 13.2 编写的,面向 iOS 13+。
首先,你想通过这样做来禁用 KQKeyboardManager
IQKeyboardManager.shared.enable = false
请注意,此行仅禁用将文本字段向上移动功能,其他 IQKeyboard 功能,如外部触摸时退出、自动工具栏等,不会被此行禁用,这通常是你想要什么。
然后,您在视图控制器的viewDidLoad 中注册键盘事件观察者,在deinit 中删除观察者。
override func viewDidLoad() {
super.viewDidLoad()
IQKeyboardManager.shared.enable = false
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
deinit {
IQKeyboardManager.shared.enable = true
NotificationCenter.default.removeObserver(self)
}
接下来,为键盘显示/隐藏添加视图向上/向下移动方法。
@objc private func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
print("keyboardSize.height", keyboardSize.height)
// using the right key here is important, because
// keyboardFrameEndUserInfoKey is an user info key
// to retrieve the keyboard’s frame at the END of its animation.
// here you move up the views you need to move up
// if you use auto layout, update the corresponding constraints
// or you update the views' frame.origin.y
// you may want to do the updates within a 0.25s animation
}
}
@objc private func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect {
// reset views to their original position on keyboard dismiss
}
}
您可能还想启用/禁用自动工具栏,因为它可能会使您的键盘高度不稳定。
// in viewDidLoad set to false, in deinit set back to true (if you need it)
IQKeyboardManager.shared.enableAutoToolbar = false