Using a scroll view to zoom in an image with Swift

2019-08-20 05:01发布

问题:

I'm learning Swift from Apple's "App Development in Swift".

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.

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.

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.

The code for the View Controller is:

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) -> 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()
}


}

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.

回答1:

Let us begin with the constraints, your scrollview was added correctly, now for your imageView, drag and drop it inside your scrollview, specify the left right top and bottom constraints the way you want and center your imageView vertically and horizontally just like the screenshots below

Let us proceed with the imageView.

Select it on your storyboard and in the assistant editor change the content mode to aspect fit like so :

Now lets move to the code,

by typing scrollView.delegate = ViewController() you are creating a new instance of type ViewController and you're not using your existing one this is why you should replace this line with :

scrollView.delegate = self

This way you will be referring to your superclass which is your existing view controller

and consider adding this too:

scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 5.0

scrollView.contentSize = .init(width: 2000, height: 2000)

Best, Marc