Automate the position of UITextField w.r.t the keyboard


/ Published in: Objective C
Save to your folder(s)

move the position of the textfield with respect to the position of the keyboard. After the last textfield has some text entered, resign the keyboard from the view


Copy this code and paste it in your HTML
  1. CGFloat animatedDistance;
  2. static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
  3. static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
  4. static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
  5. static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
  6. static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
  7.  
  8.  
  9.  
  10. - (void)textFieldDidBeginEditing:(UITextField *)textField
  11. {
  12. CGRect textFieldRect =[self.view.window convertRect:textField.bounds fromView:textField];
  13. CGRect viewRect =[self.view.window convertRect:self.view.bounds fromView:self.view];
  14. CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
  15. CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
  16. CGFloat denominator =(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)* viewRect.size.height;
  17. CGFloat heightFraction = numerator / denominator;
  18. if (heightFraction < 0.0)
  19. {
  20. heightFraction = 0.0;
  21. }
  22. else if (heightFraction > 1.0)
  23. {
  24. heightFraction = 1.0;
  25. }
  26. UIInterfaceOrientation orientation =
  27. [[UIApplication sharedApplication] statusBarOrientation];
  28. if (orientation == UIInterfaceOrientationPortrait ||
  29. orientation == UIInterfaceOrientationPortraitUpsideDown)
  30. {
  31. animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
  32. }
  33. else
  34. {
  35. animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
  36. }
  37. CGRect viewFrame = self.view.frame;
  38. viewFrame.origin.y -= animatedDistance;
  39.  
  40. [UIView beginAnimations:nil context:NULL];
  41. [UIView setAnimationBeginsFromCurrentState:YES];
  42. [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
  43.  
  44. [self.view setFrame:viewFrame];
  45.  
  46. [UIView commitAnimations];
  47.  
  48. }
  49.  
  50.  
  51.  
  52. - (void)textFieldDidEndEditing:(UITextField *)textField
  53. {
  54. CGRect viewFrame = self.view.frame;
  55. viewFrame.origin.y += animatedDistance;
  56.  
  57. [UIView beginAnimations:nil context:NULL];
  58. [UIView setAnimationBeginsFromCurrentState:YES];
  59. [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
  60.  
  61. [self.view setFrame:viewFrame];
  62.  
  63. [UIView commitAnimations];
  64. }
  65.  
  66. - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
  67.  
  68. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.