質問

I'm creating a scroll view for displaying a very large view, and I need both scroll and zoom functionality (just like an image viewer). Here are the steps that I've taken:

  1. In interface builder, I've put a scroll viewer to the view controller.
  2. I've added a pinch gesture recognizer to the scroll viewer.
  3. I've connected the gesture recognizer's action to the code to handle the gesture events.
  4. When the view controller is loaded, I change my view's origin to the center (viewer is my scroll viewer): self.viewer.contentOffset = CGPointMake(384, 512);
  5. In my code for the handler, I handled the event as such:

(startScale is 1.0 in the beginning)

- (IBAction)handlePinch:(UIPinchGestureRecognizer *)sender {
    if(sender.state == UIGestureRecognizerStateEnded){
        startScale *= sender.scale;
    }else{
        float result = sender.scale * startScale;

        self.viewer.transform = CGAffineTransformMakeScale(result, result);
    }
}

When I run the app, the gesture is recognized and scaling works correctly, however, the whole view scales with respect to the 0,0 point of the screen (top left). I want it to scale with respect to the middle point that I'm applying the gesture, just as a natural pinch gesture for zooming into a photo.

I've also tried setting self.viewer.frame's origin, but nothing changed. I've searched about the problem and found these:

How to set a UIView's origin reference? (already tried)

https://stackoverflow.com/questions/13163279/pinch-punch-gestures-center (about my problem, but unanswered)

UIPinchGestureRecognizer for zooming and panning an image in xcode (looks like an overkill, too complicated for me, and I'm not sure if this would really help my situation)

How can I achieve natural pinching with my scroll view, what am I doing wrong?

Thanks, Can.

役に立ちましたか?

解決

Well, the answer to the problem is very simple: Remove the pinch gesture altogether. The benefit of using a UIScrollView is that it handles the panning/zooming internally, and you have to do nothing

Edit: To make sure the content is scaled properly, you are going to need a UIView (called contentView or whatever you want) where you put all the content, and then on the delegate method of your UIScrollView do this:

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

This should solve your problem

Edit 2: Also remember to set the minimum / maximum zoom scales for your UIScrollView

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top