Reputation: 4632
Below code runs as expected the first time I pick an image from camera roll. Image is zoomed out propery to fit in scrollView. But when I run it again to repick an image and pick the same image again, it gets zoomed to 1.0 scale. Cannot figure out what I need to reset to make it work the same everytime. Any ideas?
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
scrollView.contentSize = CGSize(width: 0, height: 0)
picView.image = nil
picView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
picView.removeFromSuperview()
self.dismissViewControllerAnimated(true, completion: nil)
scrollView.addSubview(picView)
scrollView.contentSize = image.size
let scaleWidth = scrollView.frame.size.width / scrollView.contentSize.width //image.size.width
let scaleHeight = scrollView.frame.size.height / scrollView.contentSize.height //image.size.height
let minScale = min(scaleWidth, scaleHeight)
scrollView.minimumZoomScale = minScale
scrollView.maximumZoomScale = 1.0
scrollView.zoomScale = minScale
}
Upvotes: 2
Views: 1383
Reputation: 535284
I think you've already figured this out, but I'll just fill in what might be the missing piece of the puzzle. How does zooming actually work? As I say in my book:
The scroll view zooms by applying a scaling transform to the scalable view... Moreover, the scroll view is concerned to make scrolling continue to work correctly; ... therefore, the scroll view automatically scales its own contentSize to match the current zoomScale.
So you need to remove that transform before you start playing with the content size. Thus it might be sufficient to reset the zoomScale
to 1 up front, before you go swapping out the image view.
Even better, why not leave the image view there? You seem to be doing a lot of unnecessary work in your routine; why not think of this as a scroll view with an image view content view, where what gets swapped out is only the image?
Finally, why not use auto layout? That way, the image's size automatically becomes the image view's size, and the image view's size automatically becomes the scroll view's content size.
Upvotes: 4