Prevent UIScrollView from moving contents to top-l

2019-04-10 22:48发布

问题:

I have a UIImageView contained within a UIScrollView. The image is (usually) big, so the user can zoom it out in order to see the whole thing.

Upon zooming out, though, UIScrollView snaps the ImageView to the top-left of the scrollview. I want this to be positionable by the user, and haven't found a way to "turn it off" yet.

It's kinda like always allowing scrolling, rather then only allowing scrolling when the image is zoomed in. Maybe it's too major of a change?

Anyone know of a way? Originally, I was just going to create this functionality manually. But UIImageViews don't like to adjust to new sizes (I've tried about everything and can't get UIImageView to resize UNLESS I remove the picture from the imageView, change the frame, and re-add it).

回答1:

I ended up disabling the UIScrollView's panGestureRecognizer and subbing in a custom one.

Here's a quick snippet on how to disable it:

// Disable our GestureRecognizer
for (UIGestureRecognizer *gesture in scrollView.gestureRecognizers){
    if ([[NSString stringWithFormat:@"%@",[gesture class]] isEqualToString:@"UIScrollViewPanGestureRecognizer"]){
        [gesture setEnabled:NO];
        break;
    }
}

A bit of a hack-job there, but it's due to the fact that UIScrollViews have changed the class of the GestureRecognizer to "UIScrollViewPanGestureRecognizer." The compiler will yell at you if you try to use that class (there's probably a better solution out there).



回答2:

If you locate the UIImageView at location 0,0 in the UIScrollView, then that's always going to be the upper-left. If you want it to be centered in the scrollview when it's smaller than the view, you need to position it there. Check whether its -size is bigger or smaller than the scrollview's. If it's smaller than the scrollview, set its -center to be the same as the scrollview's.



回答3:

Check my answer on similar question here