简体   繁体   中英

How Can I Move An UIImageView Around In A UIScrollView?

In my application, I have a UIImageView inside a UIScrollView. I want to zoom and drag the UIImageView. I managed to do the zooming but I can't seem to find a way to drag the image inside the UIScrollView using touchesMoved. I have Googled around but it seems that the only method I have found was only possible in iOS 3.0+ but is now obsolete in iOS 4.0+. So how can I drag an image with my finger that is inside a UIScrollView?

You shouldn't need to do any touch detection yourself. UIScrollView can take care of everything.

Here's a example:

- (void)viewDidLoad
{
    [super viewDidLoad];

    scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.delegate = self;
    [self.view addSubview:scrollView];

    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.jpg"]];

    scrollView.contentSize = imageView.bounds.size;
    [scrollView addSubview:imageView];

    float minScale  = scrollView.frame.size.width  / imageView.frame.size.width;
    scrollView.minimumZoomScale = minScale;
    scrollView.maximumZoomScale = 2.0;
    scrollView.zoomScale = minScale;
}

Don't forget to add this delegate method to enable zooming:

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

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