在文本视图之间切换时,不同的键盘高度会产生奇怪的帧

时间:2017-05-16 15:20:57

标签: swift uikeyboard

我有一个获取电子邮件和密码的登录屏幕。密码文本字段是安全的,它会产生不同的键盘高度。当我在电子邮件文本字段和密码字段之间切换时,不首先解除键盘(在显示电子邮件键盘时单击密码),我的框架不会重新计算键盘高度,我在区域中得到黑色键盘之间的区别。 这是在我的View控制器中处理键盘的代码,显然问题是keyboardWillHide/show函数没有被再次调用,并且如果它们没有被解除则计算帧的正确高度:

    private func setupKeyboard(){
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        view.addGestureRecognizer(tap)

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func keyboardWillShow(notification: NSNotification){
        UIView.animate(withDuration: 2.0, animations: {
            self.appLogo.alpha = 0
        })
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= (keyboardSize.height)
            }
        }
    }
    func keyboardWillHide(notification: NSNotification){
        self.appLogo.alpha = 1
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != 0{
                self.view.frame.origin.y += (keyboardSize.height)
            }
        }
    }

    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        appLogo.isHidden = false
        view.endEditing(true)
    }

我正在寻找一种方法来解决这种情况,也许当我点击密码字段时,它会首先关闭电子邮件字段键盘,然后打开密码键盘。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

主要问题是您使用相对偏移(添加和减去视图的原点),而不是设置绝对值。这与一些不必要的起源检查相结合,会导致差距。试试这个:

    func keyboardWillShow(notification: NSNotification){
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        self.view.frame.origin.y = -keyboardSize.height
    }
}
func keyboardWillHide(notification: NSNotification){
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        self.view.frame.origin.y = 0
    }
}