0

I'm trying to add an image and scrollview programmatically to swift, and then allow them to be pinched to zoom.

I've followed the instructions from UIImageView pinch zoom swift but am still not able to pinch to zoom, I'm not sure what I'm missing

class mapViewController: UIViewController, UIScrollViewDelegate, IALocationManagerDelegate {

    var imageViewBackground: UIImageView!

    override func viewDidLoad() {


        super.viewDidLoad()

        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height

        let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width:width-70, height:height-60))
        var image: UIImage?
        let urlString = "https://firebasestorage.googleapis.com/v0/b/coxur-59760.appspot.com/o/Maps%2FCapture.png?alt=media&token=741b1425-cb01-453b-8c40-47f6e5fd528d"

        let url = NSURL(string: urlString)! as URL
        if let imageData: NSData = NSData(contentsOf: url) {
            image = UIImage(data: imageData as Data)
        }
        imageViewBackground.image = image

        // you can change the content mode:
        imageViewBackground.contentMode = UIView.ContentMode.scaleAspectFill

        var scrollView: UIScrollView!
        scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: width, height: height))
        scrollView.contentSize = CGSize(width: width, height: 2000)
        scrollView.delegate = self
        scrollView.minimumZoomScale = 1.0
        scrollView.maximumZoomScale = 6.0

        scrollView.addSubview(imageViewBackground)
        self.view.addSubview(scrollView)
        //self.view.sendSubviewToBack(imageViewBackground)
    }
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {

        return imageViewBackground
    }


}

What am I doing wrong here?

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    This is not relevant to the actual question you are asking, but never never never call `NSData(contentsOf: url)` with a remote URL. Download the image data asynchronously through proper means. – matt Jul 21 '19 at 19:41
  • Why is that? I'm using a remote url because I want to be able to update it after publishing the app – Griffin Hines Jul 21 '19 at 20:09
  • I didn't say don't use a remote URL. I said don't fetch it by saying `NSData(contentsOf:)`. – matt Jul 21 '19 at 21:01

2 Answers2

1

The problem is this line:

let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width:width-70, height:height-60))

Delete let. Problem solved.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

Sorry do not have the reputation to comment but could it possibly be that you are initializing the scrollView inside of the viewDidLoad instead of making it a class variable?

Omar Dadabhoy
  • 59
  • 2
  • 8