在我的 loginViewController 上有一个 textField 和一个用于搜索的 button。我想确保在 textField 中输入文本时,我的界面不会被键盘重叠,而是滚动到该键盘的大小并且可以访问所有元素。为此,我写了这段代码:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(kbDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(kbDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
@objc func kbDidShow(notification: Notification) {
guard let userInfo = notification.userInfo else { return }
let kdFrameSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
(self.view as! UIScrollView).contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height + kdFrameSize.height)
(self.view as! UIScrollView).scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: kdFrameSize.height, right: 0)
}
@objc func kbDidHide() {
(self.view as! UIScrollView).contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height)
}
当我运行应用程序时,我看到了滚动条的侧 View ,但界面本身并没有滚动。 可能是什么问题?
最佳答案
尝试使用 IQKeyboardManager 这会自动完成你的工作 链接 - https://github.com/hackiftekhar/IQKeyboardManager
你只需要在 AppDelegate 中添加这一行 在每个 View 中,所有文本字段都将自动调整。
IQKeyboardManager.sharedManager().enable = true
关于SWIFT 键盘与内容重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152515/