Iphone – Is it Possible to Center Content in a UIScrollView Like Apple’s Photos App

centeriphoneuiscrollviewuiview

I have been struggling with this problem for some time and there seems to be no clear answer. Please let me know if anyone has figured this out.

I want to display a photo in a UIScrollView that is centered on the screen (the image may be in portrait or landscape orientation).

I want to be able to zoom and pan the image only to the edge of the image as in the photos app.

I've tried altering the contentInset in the viewDidEndZooming method and that sort of does the trick, but there's several glitches.

I've also tried making the imageView the same size as the scrollView and centering the image there. The problem is that when you zoom, you can scroll around the entire imageView and part of the image may scroll off the view.

I found a similar post here and gave my best workaround, but no real answer was found:

UIScrollView with centered UIImageView, like Photos app

Best Solution

One elegant way to center the content of UISCrollView is this.

Add one observer to the contentSize of your UIScrollView, so this method will be called everytime the content change...

[myScrollView addObserver:delegate 
               forKeyPath:@"contentSize"
                  options:(NSKeyValueObservingOptionNew) 
                  context:NULL];

Now on your observer method:

- (void)observeValueForKeyPath:(NSString *)keyPath   ofObject:(id)object   change:(NSDictionary *)change   context:(void *)context { 

    // Correct Object Class.
    UIScrollView *pointer = object;

    // Calculate Center.
    CGFloat topCorrect = ([pointer bounds].size.height - [pointer viewWithTag:100].bounds.size.height * [pointer zoomScale])  / 2.0 ;
            topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );

    topCorrect = topCorrect - (  pointer.frame.origin.y - imageGallery.frame.origin.y );

    // Apply Correct Center.
    pointer.center = CGPointMake(pointer.center.x,
                                 pointer.center.y + topCorrect ); }
  • You should change the [pointer viewWithTag:100]. Replace by your content view UIView.

    • Also change imageGallery pointing to your window size.

This will correct the center of the content everytime his size change.

NOTE: The only way this content don't works very well is with standard zoom functionality of the UIScrollView.