Center view within UIScrollView on zoom

- (void)centerContent 
{
    CGFloat top = 0, left = 0;
    if (self.scrollView.contentSize.width < self.scrollView.bounds.size.width) {
        left = (self.scrollView.bounds.size.width-self.scrollView.contentSize.width) * 0.5f;
     }
    if (self.scrollView.contentSize.height < self.scrollView.bounds.size.height) {
        top = (self.scrollView.bounds.size.height-self.scrollView.contentSize.height) * 0.5f;
    }
    self.scrollView.contentInset = UIEdgeInsetsMake(top, left, top, left);
}

We call this method in UIScrollViewDelegate method:

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    [self centerContent];    
}

Don’t forget to center content in your UIScrollView setup (most likely, it is in
– (void)viewDidLoad or in scroll view setter)!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s