Can I somehow detect events from iOS keyboard?
I would like to detect this kind of events on the UIViewController
which does not have UITextField
or any sort of this kind of objects.
All I have are four circles that are UIView
and I would like to paint them in different colour when the button on the keyboard is pressed.
Swift 4.2
Register for events:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification , object:nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification , object:nil)
Selectors:
@objc func keyboardWillShow(notification: NSNotification) {
let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)
}
@objc func keyboardWillHide(notification: NSNotification) {
let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
print(keyboardHeight)
}
You are not having any object to take the input from the keyboard. To make the keyboard appear, you must have either UITextField or UITextView object in your view.
But here is the process to detect the keyboard events in your view controller. You can set observers on view controller for keyboard notifications.
To register for keyboard notification in swift 3, use write these lines in viewDidLoad() or viewWillAppear() method of your view controller
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil)
And then implement two methods keyBoardWillHide(:) and keyBoardWillShow(:) method in your view controller
func keyBoardWillShow(notification: NSNotification) {
//handle appearing of keyboard here
}
func keyBoardWillHide(notification: NSNotification) {
//handle dismiss of keyboard here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With