Tuesday, June 4, 2013

UIScrollView contentInset example in Objective C (iOS).


UIScrollView contentInset

The distance that the content view is inset from the enclosing scroll view.

@property(nonatomic) UIEdgeInsets contentInset

Discussion of [UIScrollView contentInset]
Use this property to add to the scrolling area around the content. The unit of size is points. The default value is UIEdgeInsetsZero.

UIScrollView contentInset example.
  _|←_cW_→_|_↓_
   |       |
---------------
   |content| ↑
 ↑ |content| contentInset.top
cH |content|
 ↓ |content| contentInset.bottom
   |content| ↓
---------------
  _|_______|___
             ↑

   (cH = contentSize.height; cW = contentSize.width)

Example of [UIScrollView contentInset].

// Called when the UIKeyboardWillHideNotification is sent   
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

UIScrollView contentInset example.
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    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 -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

End of UIScrollView contentInset example article.