Search code examples
iosswiftxcodeuiscrollviewuiimageview

Implementing zoom on UIScrollView


I have inserted the delagates and proper code for the zoom function to work on the UIScrollView. However when I run the code, I get a "nil" return on the minimum or maximum zoom value. I dont understand how to bypass this. Any suggestions?

import UIKit
import MapKit
import MessageUI

class ViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var tylenol: UIImageView!

    let backgroundImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()
        setBackground()

        self.scrollView.minimumZoomScale = 1.0
        self.scrollView.maximumZoomScale = 6.0
    }

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


    func setBackground() {
        view.addSubview(backgroundImageView)
        backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
        backgroundImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        backgroundImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        backgroundImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        backgroundImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

        backgroundImageView.image = UIImage(named: "background")
        view.sendSubviewToBack(backgroundImageView)
    }


Solution

  • The crash is caused by trying to unwrap one or both of your outlets which are declared as non-optional. These haven't been connected properly in the storyboard.

    @IBOutlet var scrollView: UIScrollView!
    @IBOutlet var tylenol: UIImageView!
    

    Whilst unrelated to your problem, these should be declared as follows to avoid a retain cycle:

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var tylenol: UIImageView!
    

    In your storyboard, ensure these are all set:

    Check your view controller is of the correct class check scrollview connections check Tylenol connection