Edward Hung Edward Hung - 1 year ago 202
iOS Question

Custom UIView with tapGesture

I have a drawing app. Inside my VC there are five imageViews with five colors in them. I want to be able to click on the imageView and change the stroke color. It can be easily done if I repeat myself in the viewcontroller by adding gesture Recognizers to each UIImageView and have their individual "selector" function. Such as

func redTapped() {}
func blueTapped() {}

However, I want to be able to make the code more clear by creating a custom class (ColorImageView.Swift) for these ImageViews so that when I assign the class to these buttons, they automatically gets the tap gesture and my VC automatically receives the information about which one is tapped. At the moment, I can get a "imagePressed" printed out for each image that gets assigned to my class. However, I have no way of distinguishing which one were pressed. Below are my code for ColorImageView.Swift

import Foundation

class ColorImageView: UIImageView {

private func initialize() {
let touchGesture = UITapGestureRecognizer(target: self, action: #selector(ColorImageView.imagePressed(_:)))
touchGesture.numberOfTapsRequired = 1
self.userInteractionEnabled = true

override init(frame: CGRect) {
super.init(frame: frame)

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

func imagePressed(gestureRecognizer: UITapGestureRecognizer) {
print("image pressed \(gestureRecognizer)")

My imageView names are red.png, green.png, blue.png...etc



Answer Source

You can get the tag easily.It works fine.

func imagePressed(gestureRecognizer: UITapGestureRecognizer)
   print("image pressed \(gestureRecognizer)")
   let tappedImageVIew = gestureRecognizer.view as! UIImageView
   print("image pressed \(tappedImageVIew.tag)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download