Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift detect keyboard events

Tags:

ios

swift

iphone

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.

enter image description here

like image 245
Matic1911 Avatar asked Apr 04 '17 06:04

Matic1911


2 Answers

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)
}
like image 125
Ayman Ibrahim Avatar answered Oct 07 '22 01:10

Ayman Ibrahim


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
     }
like image 45
Jitendra Solanki Avatar answered Oct 06 '22 23:10

Jitendra Solanki