Dimitris
Dimitris

Reputation: 13670

Properly zooming a UIScrollView that contains many subviews

I created a zoomable UIScrollView and added 100 subviews to it (tiled). The view scrolls perfectly left and right. However, I'd like to allow zooming.

To do so I read that my delegate needs to implement:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return ???;
}

I have seen examples that have only one subview to zoom, so they return that subview in that method. In my case, however, I have a lot more. What is the proper way to do the zooming?

I tried creating another UIView and adding the 100 subviews to that one. And then return that one view on the method above, but I doesn't work (it zooms but once it stops, it's not interactive any more).

Upvotes: 21

Views: 16128

Answers (3)

Ganesh G
Ganesh G

Reputation: 2061

You have to return what your going to add views to scroll view as a subviews.

Ex: If you are adding image view to scroll view then write

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
{
return imageView object;
}

Upvotes: 0

Lefteris
Lefteris

Reputation: 14677

Exactly,

This is what Apple also is mentioning in the Scroll View Programming Guide:

Just create a view, add all subviews to this view and add the newly created view as a single subview to the scrollview...

Then in the viewForZoomingInScrollView delegate method return the object at Index 0:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
{
    return [self.scrollView.subviews objectAtIndex:0];
}

Upvotes: 45

Dimitris
Dimitris

Reputation: 13670

I created the view where I added everything using:

UIView *zoomableView = [[UIView alloc] init];

without setting its frame.

The problem was solved when, after adding all the subviews to it, I set its frame to something large enough to accommodate all the tiled subviews.

Upvotes: 2

Related Questions