I've been working on getting the height of the keyboard in swift 4.2. I've been using the Notification Center to call a function when the keyboard shows which accepts a notification as a param, which I think is pretty standard? Here I want to calculate the height. However the notification object is missing data and I can't calculate the height.
NSConcreteNotification 0x16e43a710 {
name = UIKeyboardDidShowNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {0, 0}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {0, 0}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {0, 0}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 0}, {0, 0}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 0}, {0, 0}}";
UIKeyboardIsLocalUserInfoKey = 1;
}
}
I call a commonInit function from my init method which sets up the methods to call:
private func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
KeyboardWillShow Function
@objc private func keyboardWillShow(notification:NSNotification) {
let userInfo = notification.userInfo! as NSDictionary
let keyboardFrame = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
print(keyboardHeight)
}
Is there something missing to get the notification data?