I am trying to run a function when the keyboard shows and disappears and have the following code:
let notificationCenter = NotificationCenter.default
notific
I like the inline, block-based approach which is available for a long time already! You can read more about the parameters of addObserver(...) here.
Some advantages of this approach are:
Important: Call
NotificationCenter.default.removeObserver(observer)in thedeinitof the object where you set register the observer (often a view controller).
let center = NotificationCenter.default
let keyboardWillShowObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let height = value.cgRectValue.height
// use the height of the keyboard to layout your UI so the prt currently in
// foxus remains visible
}
let keyboardWillHideObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (notification) in
// restore the layout of your UI before the keyboard has been shown
}