3

I am using Xcode 6.4 and writing in swift.

Right now I am trying to display a simple image in aspect fit and then be able to zoom in. Unfortunately the image loads fully zoomed. Everything else works just fine, double tapping even results in seeing the image aspect fit. How could I change my code so that the image loads in aspect fit?

My case is very similar to

UIImage Is Not Fitting In UIScrollView At Start

However, the objective-c answer no longer works.

Here is my code for viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    imageView = UIImageView(image: UIImage(named: "image.png"))

    scrollView = UIScrollView(frame: view.bounds)
    scrollView.backgroundColor = UIColor.blackColor()
    scrollView.contentSize = imageView.bounds.size
    scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
    scrollView.contentOffset = CGPoint(x: 1000, y: 450)

    scrollView.addSubview(imageView)
    view.addSubview(scrollView)

    scrollView.delegate = self

    setZoomScale()
    setupGestureRecognizer()
}

And here is my code for setZoomScale()

    func setZoomScale() {
    let imageViewSize = imageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    scrollView.minimumZoomScale = min(widthScale, heightScale)
    scrollView.zoomScale = 1.0
}

All this originates from the online tutorial,

http://www.appcoda.com/uiscrollview-introduction/

Thank you in advance!

Stephen Mather
  • 275
  • 3
  • 9
  • Just a shot in the dark but could you check that the image view isn't larger than the scroll view? – Ben Aug 13 '15 at 00:07
  • If the imageview is larger than the screens bounds perhaps that could be causing it to happen – Ben Aug 13 '15 at 00:08

2 Answers2

5

Solution, in my setZoomScale function, I set the scrollView's zoomscale to "1.0" rather than the minimum

here is the corrected code, hope this helps someone!

func setZoomScale() {
    let imageViewSize = imageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    let minZoomScale = min(widthScale, heightScale)
    scrollView.minimumZoomScale = minZoomScale
    scrollView.zoomScale = minZoomScale
}
Stephen Mather
  • 275
  • 3
  • 9
1

I tried the code in Stephen Mather's answer, but it did not work until I added this UIScrollView delegate method:

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Casey Perkins
  • 1,853
  • 2
  • 23
  • 41