6
votes

I have an UIImageView with an image (map) inside of a UIScrollView. I add another image (marker) to the image view (so a map background and a marker). If the marker isn't shown on the screen, when I place the marker I want to scroll to show the marker.

I'm using [scrollView scrollRectToVisible:rect animated:YES] after I place the marker on the map. This works great when the scrollview isn't zoomed. How do I adjust rect based on the zoom scale so the marker is centered in the view?

1

1 Answers

12
votes

I do something very similar in the app I am currently working on, but instead of using -scrollRectToVisible, I use -setContentOffset.

Because I know where my marker is in the frame, I can easily calculate its center, which I save as the CGFloats centerX and centerY. I then use the following code to center the marker on the screen (I subtract 161 from the Y value because my main view has a tab bar and a navigation controller, so it is not the full 480 points):

CGFloat curZoom = scrollView.zoomScale;

[scrollView setContentOffset:CGPointMake((centerX*curZoom)-160, (centerY*curZoom)-161) animated:NO];

By multiplying the center point by the current zoomScale, I can find the correct center point regardless of zoom level.

My marker is a subview of the UIImageView that holds my map. It sounds like you are doing it the same way, so I imagine this (or something similar) should work for you.