corbin
corbin

Reputation: 2797

iOS Programmatic Zoom in UIScrollView Not Working

I'm new to iOS and I've been stuck for a while on this. My goal is to programmatically zoom to a specific spot when the user pinches anywhere in the view. This may seem strange, but it's an internal app not for the App Store. Right now, when I pinch to zoom, nothing happens.

On my View (it's a single view application), I have images that I'd like to zoom in on programmatically. Here's what I have done.

  1. In the Interface Builder, I dragged a Scroll View object onto my View, and changed the size to fit the View

  2. In the Scroll View, I set the minimum zoom = 0 and the maximum zoom = 1000 (just to make sure this wasn't the problem)

  3. I dragged a Pinch Gesture Recognizer on top of the UIScrollView.

  4. I right-clicked the UIGestureRecognizer, and created an action called handlePinch() where I placed my code to programmatically zoom when the pinch was recognized.

  5. Implemented the zoom in handlePinch (shown below)

    - (IBAction)handlePinch:(UIPinchGestureRecognizer *)sender {
        CGRect zoomRect;
    
        zoomRect.origin.x = 500;
        zoomRect.origin.y = 500;
        zoomRect.size.width = 512;
        zoomRect.size.height = 384;
    
        [scrollView zoomToRect:zoomRect animated:YES ];
      }
    

Known: - The pinch gesture is being recognized, and handlePinch is being called

Thank you for any answers or suggestions in advance!

Upvotes: 2

Views: 1771

Answers (1)

Jeffrey Sun
Jeffrey Sun

Reputation: 21

You don't need a pinch gesture to do this, since the zooming is built in. Here's what to do.

In your view controller header file, add the scroll view delegate:

@interface MyViewController : UIViewController <UIScrollViewDelegate>

Next in the implementation file, preferably in your viewDidLoad, set the scroll view's delegate to self:

- (void)viewDidLoad {
    //other stuff
    self.scrollView.delegate = self;
}

Then, copy and paste this scroll view delegate method into your implementation file:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        return self.viewToBeZoomed;
    }
}    

self.viewToBeZoomed is the view you want to zoom. This view is a subview of self.scrollView.

Upvotes: 2

Related Questions