美文网首页
Swift - 解决键盘弹出遮挡textField问题

Swift - 解决键盘弹出遮挡textField问题

作者: Hesse_Huang | 来源:发表于2016-03-09 22:11 被阅读969次

    1.先注册对键盘的监听:

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide", name: UIKeyboardWillHideNotification, object: nil)
    

    2.实现两个Selector:

    @objc private func keyboardWillShow(notification: NSNotification) {
        let info = notification.userInfo!
        let keyboardFrame = info[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let responderTextField = textFields.filter({ $0.isFirstResponder() }).first!
        
        let distanceToKeyboard = keyboardFrame.origin.y - CGRectGetMaxY(responderTextField.convertRect(responderTextField.frame, toView: view))
        
        if distanceToKeyboard < 0 {
            view.frame.origin.y -= -distanceToKeyboard
        }
    }
    @objc private func keyboardWillHide() {
        view.frame.origin.y = 0
    }
    

    但不知道为什么不需要加UIView.animateWithDuration就有了动画呢?

    3.记得要移除监听哦:

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
        NSLog("LoginViewController deinits")
    }

    相关文章

      网友评论

          本文标题:Swift - 解决键盘弹出遮挡textField问题

          本文链接:https://www.haomeiwen.com/subject/xghtlttx.html