使用自定义键盘时获得正确的键盘高度值 - SWIFT 3

时间:2016-10-07 13:08:57

标签: ios swift keyboard constraints swift3

所以我有UIButton位于UIView的底部,直到键盘出现,然后底部约束更新为键盘高度。

这适用于iOS默认键盘,但是当使用像swiftKey这样的自定义键盘时,底部约束仍然是iOS键盘高度的约束。

我注意到自定义键盘会设置三个通知而不是一个。所以这可能是问题,但我怎样才能使用正确的值?

@IBOutlet weak var fieldBottomConstant: NSLayoutConstraint!

var keyboardShowing = false

var keyboardHeight: CGFloat = 0.0

func keyboardWillShow(_ n:Notification) {

    self.keyboardShowing = true

    if let keyboardSize = (n.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
       // fieldBottomConstant.constant = keyboardSize.height
       keyboardHeight = keyboardSize.height
    }

    fieldBottomConstant.constant = keyboardHeight

}

func keyboardWillHide(_ n:Notification) {

    self.keyboardShowing = false

    fieldBottomConstant.constant = 0

}


override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(AddViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(AddViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(AddViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(AddViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(AddViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)

}

更新

我已经添加了一些通知来监视任何更改,并且在旋转设备后约束会更改为自定义键盘高度,但在首次加载键盘时仍然不使用自定义键盘高度。

2 个答案:

答案 0 :(得分:3)

答案是使用

UIKeyboardFrameEndUserInfoKey

答案 1 :(得分:1)

你应该听NSNotification.Name.UIKeyboardWillChangeFrame