Pages

Wednesday, June 1, 2011

[Code Snippet] When keyboard shows...

Sometimes we have a lot of UITextField controls in our UIView, but what happends when the keyboard is shown??? The UITextFields that are at the bottom of the UIView are hidden behind the keyboard and users don't know what they're writing.

Today's code snipett tries to help the developer to avoid this issue. What we shall do is to move the UIView up when keyboard shows and move it down again when keyboards hides. To accomplish that we have tu use observers,  and implement the two methods that will be called when keyboards shows and hides.

First, we have to add the observers to NSNotificationCenter default center for the events of showing and hiding the keyboard Implements this in viewDidLoad method.

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
 After that we implement both methods. We have to calculate the height at our hidden UITextField is, for adding or substract it from view's frame origin in order to move the UIView up and down. If we have more than one UITextField controls we shall to detect which is the first responder and sets the position accord to it.

- (void) keyboardWillShow: (NSNotification*) aNotification;
{   
    int position = 0;
   
   
    if ([textField1 isFirstResponder])
        position = 100;
    else if ([textField2 isFirstResponder])
        position = 150;
           
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    CGRect rect = [[self view] frame];
    rect.origin.y -= position;
    [[self view] setFrame: rect];
    [UIView commitAnimations];
   
}

- (void) keyboardWillHide: (NSNotification*) aNotification;
{
    int position = 0;
   
   
    if ([textField1 isFirstResponder])
        position = 100;
    else if ([textField2 isFirstResponder])
        position = 150;
   
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    CGRect rect = [[self view] frame];
    rect.origin.y += position;
    [[self view] setFrame: rect];
    [UIView commitAnimations];
}

And with this code snippet you will have a professional application that provides a good user experience and an animated interface when editing.

Enjoy it!

No comments:

Post a Comment