Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView won't pinch to zoom. (Swift)

I'm having trouble getting my UIScrollView to zoom. My code is below:

class ViewController: UIViewController, UIScrollViewDelegate {

    let imageView = UIImageView()

    @IBOutlet weak var scrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let image = UIImage(named: "cats.jpg")
        imageView.image = image
        imageView.frame = CGRect(origin: CGPointZero, size: image!.size)
        scrollView.addSubview(imageView)
        scrollView.contentSize = image!.size
        scrollView.clipsToBounds = false
        scrollView.layer.borderColor = UIColor.yellowColor().CGColor
        scrollView.layer.borderWidth = 4.0

        let scrollViewFrame = scrollView.frame
        let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
        let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
        let minScale = min(scaleWidth, scaleHeight);
        scrollView.minimumZoomScale = minScale;

        scrollView.maximumZoomScale = 1.0
        scrollView.zoomScale = minScale;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


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

}

What am I doing wrong here? I have tried adjusting the min and max scale but doesn't make any difference. Any pointers on this would be really appreciated. Thanks!

like image 660
KexAri Avatar asked Jan 07 '23 14:01

KexAri


1 Answers

Add this to viewDidLoad:

scrollView.delegate = self

The scroll view needs a delegate (your view controller) to get the view for zooming (the delegate method you implemented).

like image 157
tktsubota Avatar answered Jan 15 '23 00:01

tktsubota