Lennart P.
Lennart P.

Reputation: 376

Scrollview only zooms to upper left corner

I've created a scrollview programmatically and added an image as it's subview but when I try to zoom into the image it only zooms into the upper corner and it doesn't let me scroll around to see different parts of the image.

Here's the code I used to create the scrollview:

let scrollView = UIScrollView()

var image: NSData!

override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 3.0
    scrollView.zoomScale = 1.0
    scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
    scrollView.delegate = self
    scrollView.isPagingEnabled = false
    scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)

    view.addSubview(scrollView)

    scrollView.addSubview(imageView)

    imageView.image = UIImage(data: image as Data)
    imageView.contentMode = .scaleAspectFit
    imageView.isUserInteractionEnabled = true

    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(share))
    longPress.minimumPressDuration = 0.5
    longPress.numberOfTapsRequired = 0
    imageView.addGestureRecognizer(longPress)

    let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(recognizer:)))
    doubleTap.numberOfTapsRequired = 2
    scrollView.addGestureRecognizer(doubleTap)

}

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

func share(sender: UILongPressGestureRecognizer) {
    if sender.state == .ended {
        if UIImage(data: image as Data) != nil {
            let Item = UIImage(data: self.image! as Data)
            let activity = UIActivityViewController(activityItems: [Item!], applicationActivities: nil)
            activity.excludedActivityTypes = [UIActivityType.print, UIActivityType.addToReadingList, UIActivityType.openInIBooks]
            self.present(activity, animated: true, completion: nil)
        }
    }
}

func handleDoubleTap(recognizer: UITapGestureRecognizer) {
    if scrollView.zoomScale > scrollView.minimumZoomScale {
        scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
    } else {
        scrollView.setZoomScale(scrollView.maximumZoomScale, animated: true)
    }
}

Thank you very much for any kind of help

Upvotes: 0

Views: 847

Answers (1)

Shamas S
Shamas S

Reputation: 7549

The issue is in your code when you set the zoomscale of your scrollView. You don't specify where it should zoom to. So naturally, it zooms and stays in the top left corner.

You need to get the location of the touch in your handleDoubleTap(recognizer: UITapGestureRecognizer), calculate the rect for zoom, and call scrollRectToVisible on your scrollview.

Upvotes: 1

Related Questions