ScrollView doesn't respond after TextField input is done


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



Copy this code and paste it in your HTML
  1. ==============================
  2. DECLARATION FILE
  3. ==============================
  4. @interface ScrollViewViewController : UIViewController <UIScrollViewDelegate, UITextFieldDelegate>
  5. {
  6. UIScrollView *m_scrollView;
  7. UITextField *m_textField1;
  8. UITextField *m_textField2;
  9. }
  10.  
  11. @property(nonatomic,retain) IBOutlet UIScrollView *m_scrollView;
  12. @property(nonatomic,retain) IBOutlet UITextField *m_textField1;
  13. @property(nonatomic,retain) IBOutlet UITextField *m_textField2;
  14.  
  15. - (void)scrollViewToCenterOfScreen:(UIView *)theView;
  16.  
  17. @end
  18.  
  19. ==============================
  20. IMPLEMENTATION FILE
  21. ==============================
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24.  
  25. m_scrollView.contentSize = CGSizeMake(320, 1000);
  26. [self.view addSubview:m_scrollView];
  27. }
  28.  
  29. ...
  30. #pragma mark * TextField Delegate Methods
  31. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  32. {
  33. [textField resignFirstResponder];
  34. return NO;
  35. }
  36.  
  37. - (void)textFieldDidBeginEditing:(UITextField *)textField
  38. {
  39. [self scrollViewToCenterOfScreen:textField];
  40. }
  41.  
  42. - (void)scrollViewToCenterOfScreen:(UIView *)theView
  43. {
  44. CGRect keyboardBounds;
  45. CGFloat viewCenterY = theView.center.y;
  46. CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
  47.  
  48. CGFloat availableHeight = applicationFrame.size.height - keyboardBounds.size.height; // Remove area covered by keyboard
  49.  
  50. CGFloat y = viewCenterY - availableHeight / 2.0;
  51. if (y < 0) {
  52. y = 0;
  53. }
  54. m_scrollView.contentSize = CGSizeMake(applicationFrame.size.width, applicationFrame.size.height + keyboardBounds.size.height);
  55. [m_scrollView setContentOffset:CGPointMake(0, y) animated:YES];
  56. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.