Get the frame of the keyboard dynamically Get the frame of the keyboard dynamically ios ios

Get the frame of the keyboard dynamically


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 rotationint height = MIN(keyboardSize.height,keyboardSize.width);int width = MAX(keyboardSize.height,keyboardSize.width);//your other code here..........}

Tutorial for more information


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.


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!")}