Monday, 18 June 2012

Making the view slide up to make room for the keyboard



In my application i had many UITextFields which covered my whole UIViewController.
When i touched my UITextField which was at bottom to enter data, i came to know that the Virtual Keyboard came in front of it and covered it. So i was in a trouble after some help from StackOverflow i resolved the problem.

Add a UIScrollview - scrollView to your UIView and set delegates for UITextFields & UIScrollview

  - (BOOL)textFieldShouldReturn:(UITextField *)textField
  {
     if (textField == txtFieldName)
   {
         [txtFieldCellNo becomeFirstResponder];
   }
   else if (textField == txtFieldCellNo)
   {
         [txtFieldEmail becomeFirstResponder];
   }
   else
  {
       [textField resignFirstResponder];

  }
return YES;
}

 - (void)textFieldDidBeginEditing:(UITextField *)textField
 {
     if(textfield == txtFieldName)
       [self animateTextField:txtFieldName up:YES: 80];
     else if(textField == txtFieldCellNo)
       [self animateTextField: txtFieldCellNo up:YES: 100];

     else if(textField == txtFieldEmail)
       [self animateTextField: txtFieldEmail up:YES: 120];

 }


- (void)textFieldDidEndEditing:(UITextField *)textField
{
     if(textfield == txtFieldName)
       [self animateTextField:txtFieldName up:NO: 80];
     else if(textField == txtFieldCellNo)
       [self animateTextField: txtFieldCellNo up:NO: 100];

     else if(textField == txtFieldEmail)
       [self animateTextField: txtFieldEmail up:NO: 120];

}


- (void) animateTextField: (UITextField*) textField up: (BOOL) up: (int) distance
{
    const int movementDistance = distance;
    const float movementDuration = 0.3f;
    int movement = (up ? -movementDistance : movementDistance);
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.scrollView.frame = CGRectOffset(self.scrollView.frame,0, movement);
    [UIView commitAnimations];
}

Here i have changed the movementDistance by 80 for txtFieldName, 100 for txtFieldCellNo and 120 for txtFieldEmail. This means my scrollview will scroll screen by 80, 100 and 120 pixels towards top.

You must adjust/change movementDistance to a value required for your UITextField.


No comments:

Post a Comment