iPhone Development 101

iPhone 101

Code Tips

Resources

More

iPhone (English): iPad (English):
iPhone portrait: 320 x 216, Landscape: 480 x 162 iPad portrait: 768 x 264, Landscape: 1024 x 352

The size of the on-screen keyboard varies based on the device and language used. Your app can get the exact keyboard size by registering as an observer for one of these notifications:

UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification

Example:

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:)        
                                                 name:@"UIKeyboardWillShowNotification" 
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardDidHide:)        
                                                 name:@"UIKeyboardDidHideNotification" 
                                               object:nil];
}

The keyboard will overlap text fields in the lower half of the screen. To move the view up when the keyboard appears, add this animation code to the UIKeyboardWillShowNotification callback:

- (void) keyboardWillShow:(NSNotification *)note {
    NSDictionary *userInfo = [note userInfo];
    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    NSLog(@"Keyboard Height: %f Width: %f", kbSize.height, kbSize.width);

    // move the view up by 30 pts 
    CGRect frame = self.view.frame; 
    frame.origin.y = -30;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = frame;
    }];
}

To move the view down again after the keyboard disappears, add a UIKeyboardDidHideNotification callback with the following animation:

- (void) keyboardDidHide:(NSNotification *)note {

    // move the view back to the origin
    CGRect frame = self.view.frame; 
    frame.origin.y = 0;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = frame;
    }];
}

Be sure to remove the object from the notification center on dealloc (even in ARC projects):

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // uncomment for non-ARC:
    // [super dealloc];
}

Additional References:

Back to Top

TopHome