Search code examples
iosswiftscrollview

Cannot Zoom UIImageView


I am new to swift.

I am doing an exercise from an app development book. I am trying to create an UIImageView and put a image in it, but I can not zoom the image in. There is something wrong in my code, but I don't know what is going on.

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {


    @IBOutlet weak var image: UIImageView!
    @IBOutlet weak var scroll: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()
        scroll.delegate = ViewController()
        updateZoomFor(size:view.bounds.size)
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    private func viewForZooming(in scrollView: UIScrollView) -> UIImageView{
        return image
    }

    func updateZoomFor(size:CGSize){
        let widthScale = size.width / image.bounds.width
        let heightScale = size.height / image.bounds.height
        let scale = min(widthScale, heightScale)
        scroll.minimumZoomScale = scale
    }

}

Solution

  • First, set scroll.delegate = self as suggested by 3stud1ant3.

    Second, you need to match the definition of theUIScrollViewDelegate method:

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

    Make sure you set the zoom scale in updateZoomFor as well: scroll.zoomScale = scale.

    Also you need to implement this:

    override func viewWillLayoutSubviews() {  
      super.viewWillLayoutSubviews()
      updateZoomFor(size: view.bounds.size)
    }
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
      updateConstraintsForSize(view.bounds.size)
    }
    
    fileprivate func updateConstraintsForSize(_ size: CGSize) {
    
      let yOffset = max(0, (size.height - imageView.frame.height) / 2)
      imageViewTopConstraint.constant = yOffset
      imageViewBottomConstraint.constant = yOffset
    
      let xOffset = max(0, (size.width - imageView.frame.width) / 2)
      imageViewLeadingConstraint.constant = xOffset
      imageViewTrailingConstraint.constant = xOffset
    
      view.layoutIfNeeded()
    }