Search code examples
iosswiftuiscrollviewuiimageview

UIImageView Pinch Zoom and Drag swift


I am using below code to zoom the image but my imageView is getting zoomed above 4 scale factor and then I try to drag the imageView it zoomed out to 4 scale factor.

How to stop it from zoomed above the 4 scaleFactor or How to stop it from zooming out when we drag?

class ZoomViewController: UIViewController,UIScrollViewDelegate {

@IBOutlet weak var scrollView:UIScrollView!
@IBOutlet weak var imageView:UIImageView!

override func viewDidLoad() {

        super.viewDidLoad()
        scrollView.delegate = self

        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 4.0
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
}


Solution

  • You can get that working by implementing UIScrollViewDelegate's scrollViewDidZoom(_:) method, i.e.

    func scrollViewDidZoom(_ scrollView: UIScrollView) {
        if scrollView.zoomScale > scrollView.maximumZoomScale {
            scrollView.zoomScale = scrollView.maximumZoomScale
        } else if scrollView.zoomScale < scrollView.minimumZoomScale {
            scrollView.zoomScale = scrollView.minimumZoomScale
        }
    }
    

    In the above code, check if the scrollView's zoomScale lies within maximumZoomScale and minimumZoomScale. If it doesn't, update it as per the limits allowed.