Reputation: 113
I am trying to play around with the UIImageView. I want something that when I tap the image, it makes the image 2x its size (always make it twice the size so if I tap more than once it keeps getting bigger).
This is what I currently have and I am not sure how to build the handlePan
function that I originally wanted to use. I used the pan gesture because I don't know how to approach the tap gesture specifically. If my code is not on the right direction, please feel free to suggest what would work best. I would really appreciate any input.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var ImageView1: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let gesterRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) //handlePan is the tap function I am trying to build
ImageView1.isUserInteractionEnabled = true
ImageView1.addGestureRecognizer(gesterRecognizer)
}
}
Upvotes: 0
Views: 914
Reputation: 2666
As mentioned in the comments, first of all you need a tap gesture recognizer instead of pan gesture one. In following code you will be able to double the width and height of image each time a user tap's on imageView.
In this implementation I wanted to animate the transition with 0.5 seconds, which is not necessary but it might look better to do it this way. Also assuming that you want image to be at center at all times, you need to set center to frame's center so it wont float around as the frame of image changes. But if you wish to have a different layout or positioning, you need to update the following line:
self.imageView.center = self.view.center
Also you need to enable imageView's user interaction property, by setting it true.
import UIKit
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func handleTap() {
UIView.animate(withDuration: 0.5) {
self.imageView.frame.size.height *= 2
self.imageView.frame.size.width *= 2
self.imageView.center = self.view.center
}
}
}
Upvotes: 1