/ Published in: Objective C
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
============================== DECLARATION FILE ============================== @interface ScrollViewViewController : UIViewController <UIScrollViewDelegate, UITextFieldDelegate> { UIScrollView *m_scrollView; UITextField *m_textField1; UITextField *m_textField2; } @property(nonatomic,retain) IBOutlet UIScrollView *m_scrollView; @property(nonatomic,retain) IBOutlet UITextField *m_textField1; @property(nonatomic,retain) IBOutlet UITextField *m_textField2; - (void)scrollViewToCenterOfScreen:(UIView *)theView; @end ============================== IMPLEMENTATION FILE ============================== - (void)viewDidLoad { [super viewDidLoad]; m_scrollView.contentSize = CGSizeMake(320, 1000); [self.view addSubview:m_scrollView]; } ... #pragma mark * TextField Delegate Methods - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } - (void)textFieldDidBeginEditing:(UITextField *)textField { [self scrollViewToCenterOfScreen:textField]; } - (void)scrollViewToCenterOfScreen:(UIView *)theView { CGRect keyboardBounds; CGFloat viewCenterY = theView.center.y; CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame]; CGFloat availableHeight = applicationFrame.size.height - keyboardBounds.size.height; // Remove area covered by keyboard CGFloat y = viewCenterY - availableHeight / 2.0; if (y < 0) { y = 0; } m_scrollView.contentSize = CGSizeMake(applicationFrame.size.width, applicationFrame.size.height + keyboardBounds.size.height); [m_scrollView setContentOffset:CGPointMake(0, y) animated:YES]; }