Get the frame of the keyboard dynamically

46,036

Solution 1

try this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(keyboardWasShown:)
                                         name:UIKeyboardDidShowNotification
                                       object:nil];

- (void)keyboardWasShown:(NSNotification *)notification
{

// Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

//Given size may not account for screen rotation
int height = MIN(keyboardSize.height,keyboardSize.width);
int width = MAX(keyboardSize.height,keyboardSize.width);

//your other code here..........
}

Tutorial for more information

Solution 2

Just follow this tutorial from Apple and you will get what you want. Apple Documentation. In order to determine the area covered by keyboard please refer to this tutorial.

Solution 3

For the Swift 3 users, the @Hector code (with some additions) would be:

In your viewDidLoad add the observer :

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: .UIKeyboardDidShow , object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: .UIKeyboardDidHide , object: nil)

Then implement those methods:

func keyboardDidShow(_ notification: NSNotification) {
     print("Keyboard will show!")
     // print(notification.userInfo)

     let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size
     print("Keyboard size: \(keyboardSize)")  

     let height = min(keyboardSize.height, keyboardSize.width)
     let width = max(keyboardSize.height, keyboardSize.width)

}

func keyboardDidHide(_ notification: NSNotification) {
        print("Keyboard will hide!")
}
Share:
46,036
lu yuan
Author by

lu yuan

http://www.seeyoukee.com

Updated on March 13, 2020

Comments

  • lu yuan
    lu yuan about 4 years

    Is it possible to get the frame, actually its height, of the keyboard dynamically? As I have a UITextView and I would like to adjust its height according to the keyboard frame height, when the input method of the keyboard is changed. As you know, different input methods may have different keyboard frame height.