在swift中不使用NSNotification计算键盘高度

时间:2017-11-22 05:21:03

标签: swift nsnotificationcenter uikeyboard

我有一个非常小的问题 - 我们可以使用通知计算键盘高度。所有利益溢出的答案都在使用NSNotification但是有更简单的计算方法吗?

下面是代码:

 NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil

@objc func keyboardWillShow(notification:  ) {
    if let userInfo = notification.userInfo {
        if let keyboardSize =  (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let kbHeight = keyboardSize.height

            }
        }
    }

在textFieldDidBeginEditing中使用键盘高度的代码:

var kbHeight: CGFloat?


@objc func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardSize =  (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            kbHeight = keyboardSize.height

            }
        }
    }


func textFieldDidBeginEditing(_ textField: UITextField) {

    if textField.frame.maxY > self.kbHeight!
    {
        self.scrollView.setContentOffset(CGPoint.init(x: 0, y: textField.frame.maxY - (self.kbHeight! + 2.0)), animated: true)

    }

    else{
        return
    }

    print(textField.frame.maxY)
    print(self.view.frame.height * 0.6)
    print(textField.frame.maxY - self.view.frame.height * 0.6)

}



func textFieldDidEndEditing(_ textField: UITextField)
{
self.scrollView.setContentOffset(CGPoint.init(x: 0, y: 0), animated: true)

self.view.endEditing(true);
}

1 个答案:

答案 0 :(得分:-1)

实际上我并不知道直接获得键盘高度..但是当键盘存在时你可以将键盘高度保存在变量中并在你想要的地方使用它们

将这两个观察者用于键盘并管理键盘高度

    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)

当弹出或关闭视图控制器时,必须在dinit方法中删除这些观察者。

deinit {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

键盘通知的选择器方法......

 @objc func keyboardWillShow(notification: NSNotification) {
    var keyBoardHeight: CGFloat = 0
    if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        keyBoardHeight = keyboardRectangle.height

    }
}

@objc func keyboardWillHide(notification: NSNotification) {
}