How to Assign an Action for Uiimageview Object in Swift

How to assign an action for UIImageView object in Swift

You'll need a UITapGestureRecognizer.
To set up use this:

override func viewDidLoad()
{
super.viewDidLoad()

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
}

@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView

// Your action
}

(You could also use a UIButton and assign an image to it, without text and than simply connect an IBAction)

UITapGestureRecognizer Action on UIImageView in swift

//set in ViewDidLoad

imagePhotoControl.userInteractionEnabled = true ;

iOS Swift: Send action (control event) from subclass of UIImageView

I will recommend you to use a closure to handle taps:

class TappableImageView: UIImageView {

var handleTap: (() -> Void)? = nil


//------------------------------------------
private func addTapGesture(){
let tapOnImage = UITapGestureRecognizer(target: self, action: #selector(TappableImageView.handleTapGesture(tapGesture:)))
self.isUserInteractionEnabled = true
self.addGestureRecognizer(tapOnImage)

}


//----------------------------------------------
@objc func handleTapGesture(tapGesture: UITapGestureRecognizer) {
handleTap?()
}
}

And then I your view controller you can use this i.e. in viewDidLoad method:

override func viewDidLoad() {
super.viewDidLoad()
yourTappableImageView.handleTap = {
print("an image view was tapped")
}
}

It assumes that your TappableImageView is stored in variable named yourTappableImageView.

How to make a UIImageView tappable and cause it to do something? (Swift)

Once you've create the view, you need to set it's userInteractionEnabled property to true. Then you need to attach a gesture to it.

imageView.userInteractionEnabled = true
//now you need a tap gesture recognizer
//note that target and action point to what happens when the action is recognized.
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped:"))
//Add the recognizer to your view.
imageView.addGestureRecognizer(tapRecognizer)

Now you still need the function, in this case imageTapped:, which is where the action happens when the gesture is recognized. The gesture that was recognized will be sent as an argument, and you can find out which imageView was tapped from they gestures view property.

func imageTapped(gestureRecognizer: UITapGestureRecognizer) {
//tappedImageView will be the image view that was tapped.
//dismiss it, animate it off screen, whatever.
let tappedImageView = gestureRecognizer.view!
}


Related Topics



Leave a reply



Submit