Dealing with Keyboards…

You know when you have something like two UITextFields and a UIButton (for a registration screen, for example…). The bad part when one of the UITextFields becomes the first responder, sometimes the keyboard puts itself on top of the UIButton. This piece of code, creates a nice effect to animate the UIButton (or anything you want really):


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

And the callback:


- (void)keyboardWillShow:(NSNotification*)notification

{

   // Get the duration of the keyboard animation

   NSDictionary* info = [notification userInfo];

   NSValue* value = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];

   NSTimeInterval duration = 0;

   [value getValue:&duration];

   // Get the keyboard frame

   CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

   // calculate the final Y position

   CGFloat buttonYPosition = self.view.frame.size.height - keyboardFrame.size.height - self.myButton.frame.size.height - 5.0f;

   // Animate the button to the right place

   [UIView animateWithDuration:duration animations:^
   {
      [self.myButton setFrame:CGRectMake(self.myButton.frame.origin.x, buttonYPosition, self.myButton.frame.size.width, self.myButton.frame.size.height)];
   }];
}

The important part is:

  1. You are able to calculate exactly the size of the keyboard and play with it.
  2. You get the time of the animation for the keyboard, so you can animate at the same speed.

If you have a really long UIView, you can replace this technic, with a UIScrollView.

Advertisements
Tagged , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: