Wednesday, June 5, 2013

UIScrollView setContentOffset example in Objective C (iOS).


UIScrollView setContentOffset

Sets the offset from the content view’s origin that corresponds to the receiver’s origin.

- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated

Parameters of [UIScrollView setContentOffset]
contentOffset
A point (expressed in points) that is offset from the content view’s origin.
animated
YES to animate the transition at a constant velocity to the new offset, NO to make the transition immediate.

UIScrollView setContentOffset example.
- (void)scrollToPage:(int)page
{
    UIScrollView *scrollView = contentView;
    CGPoint offset = CGPointMake(scrollView.bounds.size.width * page,
                                 scrollView.contentOffset.y);

    [UIView animateWithDuration:.5
                          delay:0
                        options:UIViewAnimationCurveEaseInOut
                     animations:^{
                         [scrollView setContentOffset:offset animated:NO];
                     } completion:nil];

    [self pageControlUpdate];
}

Example of [UIScrollView setContentOffset].
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    svos = scrollView.contentOffset;
    CGRect rect = [textView bounds];
    rect = [textView convertRect:rect toView:self.scrollView];
    CGPoint point = rect.origin ;
    point.x = 0 ;
    [self.scrollView setContentOffset:point animated:YES];
    doneButton.enabled = YES;
}

- (IBAction)donePressed
{
    [scrollView setContentOffset:svos animated:YES];
    [textview resignFirstResponder];
    doneButton.enabled = NO;
}

UIScrollView setContentOffset example.
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height);
[self.scrollView setContentOffset:bottomOffset animated:YES];

End of UIScrollView setContentOffset example article.