I was hoping someone could help me out. I am trying to allow a user to pinch zoom on a UIImageView(with a max and min level allowed). But for some reason the it does not work right. The image zooms a little then just bounces back. Thank you.
here is the zoom func
func zoom(sender:UIPinchGestureRecognizer) {
if sender.state == .Ended || sender.state == .Changed {
let currentScale = self.view.frame.size.width / self.view.bounds.size.width
var newScale = currentScale*sender.scale
if newScale < 1 {
newScale = 1
}
if newScale > 9 {
newScale = 9
}
let transform = CGAffineTransformMakeScale(newScale, newScale)
self.imageView?.transform = transform
sender.scale = 1
}
}
Swift 3 solution
This is the code I used. I added imageView to scrollView as a subview.
In my view, the problem is your determination of currentScale. It always equals 1, because you change the scale of your imageView. You should assign your currentScale as follows:
I think the biggest problem is at the end of your
func
, you havesender.scale = 1
. If you remove that line of code, your image shouldn't just bounce back each time.I posted an answer here for zoom functionality with both pinch and double tap in Swift 3. Works perfectly.
This is an old question but I don't see any answers that explain what is wrong with the original code.
This line:
Is working on the main view rather than the imageView so the scale calculation is always ~1
This simple change makes it behave as expected
by changing self to sender (and forcing view to unwrap) the scale calculation works as expected.
I decided to add the imageView to a UIScrollView. It allows the user to zoom and pan over. Here is the code I used.
in order to set max/min zoom I used :
here is the rest of the code.
I also had to add this as well
Swift 3 & above function prototype