Phillip
Phillip

Reputation: 4306

UIScrollView moves image to the top left corner when zooming in

Looking at this question: Prevent UIScrollView from moving contents to top-left, i'm having the exact issue.

I'm using this tutorial: http://cocoadevblog.heroku.com/iphone-tutorial-uiimage-with-zooming-tapping-rotation

Back to the similar question, if i disable the UIScrollViewPanGestureRecognizer, i'm not able to pan the zoomed image anymore.

I have a UIImageView within a UIScrollView, and i want to be able to zoom and pan the image as well.

How can i do tho disable the contents moving to the top left corner when zooming in?

Upvotes: 1

Views: 5339

Answers (4)

Tanya Berezovsky
Tanya Berezovsky

Reputation: 91

If I understand you right, you want to allowing scrolling only when theImageView is zoomed in, then a scrollView.zoomScale > 1. For my app requirement I am using this.

Add UIScrollView's delegate method as follows and check.

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    CGFloat offsetY = 0;
    if (aScrollView.zoomScale > 1)
        offsetY = aScrollView.contentOffset.y;

    [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, offsetY)];
}

Upvotes: 0

kensanwa
kensanwa

Reputation: 11

Just in case anyone else comes here and none of the other answers seem to work ( which was my case ), what did the trick for me was setting the contentSize of the scrollView. Just set it to the size whatever subview you are zooming in on and it should work.

Upvotes: 1

Phillip
Phillip

Reputation: 4306

Seems i solved tweaking my UiScrollView Autosizing and Origin in the Size inspector \ Attributes inspector. I unchecked Paging Enabled and the magic happened.

Upvotes: 2

GWed
GWed

Reputation: 15653

Make a subclass of UIScrollView, and add this method to it:

- (void)layoutSubviews {
    [super layoutSubviews];

    // center the image as it becomes smaller than the size of the screen
    CGSize boundsSize = self.bounds.size;

    //get the subView that is being zoomed
    UIView *subView = [self.delegate viewForZoomingInScrollView:self];

    if(subView)
    {
    CGRect frameToCenter = subView.frame;

    // center horizontally
    if (frameToCenter.size.width < boundsSize.width)
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
    else
        frameToCenter.origin.x = 0;

    // center vertically
    if (frameToCenter.size.height < boundsSize.height)
        frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
    else
        frameToCenter.origin.y = 0;

    subView.frame = frameToCenter;
    }

    else
        NSLog(@"No subView set for zooming in delegate");
}

Upvotes: 0

Related Questions