A.Roe A.Roe - 1 month ago 40
Swift Question

Getting correct value of keyboard height when using custom keyboards - SWIFT 3

So I have a

UIButton
which sits at the bottom of the
UIView
until the keyboard appears then the bottom constraint is updated to the keyboard height.

This works fine with the iOS default keyboard, but when using a custom keyboard like swiftKey the bottom constraint is still that of the iOS Keyboard height.

I have noticed that a custom keyboard sets off three notifications instead of one. So this may be the issue but how can I use the correct value ?

@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)

}


UPDATE

I have added some more notifications to watch for any changes, and the constraints change to the custom keyboard height after rotating the devices however still do not use the custom keyboard height when the keyboard is first loaded.

Answer

The answer was to use

UIKeyboardFrameEndUserInfoKey
Comments