markhorrocks
markhorrocks

Reputation: 1518

Swift How to pan UIImage in UiImageView?

I have a simple test application and I want to pan an image inside its view. It will not pan or zoom and I can't see what's wrong with my code.

I have followed this tutorial but implemented it in code. I've made the image width the same as the height so I can pan without necessarily zooming.

Here is my code

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

    let scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        return scrollView
    }()

    let zoomImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.isUserInteractionEnabled = true
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.image = #imageLiteral(resourceName: "lighthouse")
        return imageView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white 

        let screenSize = UIScreen.main.bounds
        let screenHeight = screenSize.height

        scrollView.frame = CGRect(x:0, y:0, width: screenHeight, height: screenHeight)
        scrollView.delegate = self
        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 3.0

        zoomImageView.frame = CGRect(x:0, y:0, width: screenHeight, height: screenHeight)

        scrollView.addSubview(self.zoomImageView)

        view.addSubview(scrollView)
    }

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

Upvotes: 0

Views: 1281

Answers (1)

matt
matt

Reputation: 535557

Search in your code for the term contentSize. You don't see it, do you? But the most fundamental fact about how a scroll view works is this: a scroll view without a contentSize cannot scroll (i.e. "pan" as you put it). In particular, it must have a content size larger than its own bounds size in order to be able to scroll along that axis (height or width, or both). Otherwise, there is nothing to scroll.

Upvotes: 2

Related Questions