SWIFT键盘与内容重叠

时间:2018-07-03 10:40:45

标签: swift notifications uiscrollview

在我的loginViewController上,有一个 textField 按钮用于搜索。我想确保在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)
    }

运行应用程序时,我具有滚动条的侧视图,但是界面本身不滚动。 可能是什么问题?

2 个答案:

答案 0 :(得分:1)

尝试使用IQKeyboardManager,这将自动完成您的工作 链接-https://github.com/hackiftekhar/IQKeyboardManager

您只需要在AppDelegate中添加此行 在每个视图中,所有文本字段都会自动调整。

IQKeyboardManager.sharedManager().enable = true

答案 1 :(得分:0)

更改内容偏移,而不是设置contentSize。

 @objc func kbDidShow(notification: Notification) {
    guard let userInfo = notification.userInfo else { return }
    let kdFrameSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    (self.view as! UIScrollView).contentOffset.y +=  kdFrameSize.size.height
    (self.view as! UIScrollView).scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: kdFrameSize.height, right: 0)
}