简体   繁体   中英

Cannot pan UIScrollView after zooming

I've programatically created a UIScrollView using the following code:

.h:

@interface MainController : UIViewController <UIScrollViewDelegate>

@property (nonatomic, retain) UIScrollView *mainScrollView;
@property (nonatomic, retain) UIView *mainView;

.m:

- (void) initVariables
{
    // Setters

    screenRect = [[UIScreen mainScreen] bounds];
    screenWidth = screenRect.size.width;
    screenHeight = screenRect.size.height;

    // Alloc-init methods
    mainScrollView = [[UIScrollView alloc] init];
    mainView = [[UIView alloc] init];
}

- (void) setUpScrollView
{
    mainScrollView.frame = CGRectMake(0.0f, 0.0f, screenWidth, screenHeight);
    mainScrollView.contentSize = CGSizeMake(screenWidth*2, screenHeight*2);
    mainScrollView.minimumZoomScale = 1.0;
    mainScrollView.maximumZoomScale = 4.0;
    mainScrollView.backgroundColor = [UIColor blueColor];
    mainScrollView.scrollEnabled = YES;
    mainScrollView.delegate = self;

    mainView.frame = CGRectMake((screenWidth/2) - 25.0f, (screenHeight/2) - 25.0f, 50.0f, 50.0f);

    UIImageView *testImageView = [[UIImageView alloc] init];
    testImageView.backgroundColor = [UIColor redColor];
    testImageView.frame = CGRectMake(0.0f, 0.0f, 50.0f, 50.0f);

    // Add subviews

    [self.view addSubview:mainScrollView];
    [mainScrollView addSubview:mainView];
    [mainView addSubview:testImageView];

}

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

The zoom works well now. However, I can only pan when the UIScrollView is at the minimum zoom. All other times, when I pinch-zoom in, when I release my fingers the UIView shifts slightly off-centre, despite being centred when I was zooming, and I can no longer pan the UIScrollView.

Also, after zooming in, if I zoom back out again to minimum zoom, I still cannot pan.

TL;DR - In other words, UIScrollView's pan only before using the pinch zoom feature, after which it breaks.

How can I prevent this from happening, and allow the UIScrollView's pan to always be enabled? All help appreciated.

Try to add another view in scrollView with same size of screen and then add mainView and imageView. It may solve your proble. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM