Dailycode.info

Short solution for short problems

iOS : scroll TextView or TextField

Very soon you will bump into the keyboard coming in front of your TextField or TextView.

I found a good solution on stack overflow and improved it a little. It didn't support orientation changes.

First you'll need to register the keyboard shown and hidden methods in your ViewDidLoad:

...
[selfregisterForKeyboardNotifications];
...
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenterdefaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenterdefaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

 

Now for your TextFields (not needed for UITextView) implement these methods from the delegate UITextFieldDelegate:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeField = textField;
}
 
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    activeField =nil;
}

They need the variable active field to be declared somewhere in your implementation:

UIView * activeField;

Then the trick is implementing these to methods. They are called when the keyboard is shown or hidden:

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIDeviceOrientation orientation = [[UIDevicecurrentDevice] orientation];
    UIEdgeInsets contentInsets;
    CGFloat height;
    if (UIInterfaceOrientationIsPortrait(orientation))
    {
        height = kbSize.height;
    }
    else
    {
        height =  kbSize.width;
    }
    contentInsets = UIEdgeInsetsMake(0.0, 0.0, height, 0.0);
    self.scrollview.contentInset = contentInsets;
    self.scrollview.scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= height;
    CGPoint origin = activeField.frame.origin;
    origin.y -= self.scrollview.contentOffset.y;
    if (!CGRectContainsPoint(aRect, origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-(aRect.size.height));
        [self.scrollview setContentOffset:scrollPoint animated:YES];
    }
}
 
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollview.contentInset = contentInsets;
    self.scrollview.scrollIndicatorInsets = contentInsets;
}