title: Using a scroll view to zoom in an image with Swift
body: <p>I'm learning Swift from Apple's "App Development in Swift".</p>
  
  <p>I'm having problems with constraints, especially on the "I Spy" lab at page 593. It basically wants you to create a scroll view with an image view inside it and make it so you can zoom in an image and scroll it, like in the Photos app when you open a photo.</p>
  
  <p>The book says to make both the scroll view and the image view as big as the screen with constraints, so I add top, bottom, leading and trailing constraints to 0, and it works fine.</p>
  
  <p><a href="https://i.stack.imgur.com/gCJjq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gCJjq.png" alt=""></a></p>
  
  <p>When I add the Image View I start getting problems. If I set the same constraints as the scroll view, it says that it's missing constraints for X and Y positions, and it doesn't work.
  If I do add those constraints, so I make it aligned horizontally and vertically, the image just stretches to the screen, but I still can't zoom or scroll.</p>
  
  <p><a href="https://i.stack.imgur.com/wCZwG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wCZwG.jpg" alt=""></a></p>
  
  <p>The code for the View Controller is:</p>
  
  <pre><code>class ViewController: UIViewController, UIScrollViewDelegate {
  
  @IBOutlet weak var scrollView: UIScrollView!
  @IBOutlet weak var imageView: UIImageView!
  
  override func viewDidLoad() {
      super.viewDidLoad()
      scrollView.delegate = ViewController()
      updateZoomFor(size: view.bounds.size)
  }
  
  func viewForZooming(in scrollView: UIScrollView) -&gt; UIView? {
      return imageView
  }
  
  func updateZoomFor(size: CGSize){
      let widthScale = size.width / imageView.bounds.width
      let heightScale = size.height / imageView.bounds.height
      let scale = min(widthScale,heightScale)
      scrollView.minimumZoomScale = scale
  }
  
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
  }
  
  
  }
  </code></pre>
  
  <p>I tried looking around on the internet but didn't find anything. I hope this isn't a stupid question, but I tried to figured this out for a day now.</p>