Tag Archives: UIView

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.

Tagged , , , ,
Note: Just a small design tip I am using on a project. 
When there are just too many UIGesturesRecognizers you need to use on a UIView, something I would recommend is to implement a state machine. Normally, you wouldn’t use the UIGesturesRecognizers at the same time, but at different phases like:
  • Moving subviews
  • ToolBox for the subviews
  • Resizes
  • Adding new subviews at a given location

Start by defining a typedef:

// Defines the state of the View
typedef enum {
    addFigureState = 0,
    resizeFigureState = 1,
    normalState = 2
} SCDrawViewState;

Depending on the phase you are, just [gesture setEnable:YES] or [gesture setEnable:NO]

UIView with too many UIGesturesRecognizer

Tagged , , , , ,