How to write a generic method for UITapGestureRecognizer using swift

500 views Asked by At

I have to add tapGesture for labels and ImageView. How can I create a generic tap gesture method for Labels and ImageView?

//TapGestureHandler
extension EditViewController : UIGestureRecognizerDelegate
{
 //Add Gesture on ImageView
 func addGesture()
 {
    //Gesture Male
    let maleTapGesture = UITapGestureRecognizer(target: self, action: #selector(maleGestureTap))
    maleTapGesture.delegate = self
    imgViewMale.addGestureRecognizer(maleTapGesture)

    //GestureFemale
    let FemaleTapGesture = UITapGestureRecognizer(target: self, action: #selector(femaleGestureTap))
    FemaleTapGesture.delegate = self
    imgViewFemale.addGestureRecognizer(FemaleTapGesture)

    //Gesture MaleFemale
    let maleFeTapGesture = UITapGestureRecognizer(target: self, action: #selector(maleFeGestureTap))
    maleFeTapGesture.delegate = self
    imgViewMaleFe.addGestureRecognizer(maleFeTapGesture)
 }

 //Tap Gesture Male
 func maleGestureTap()
 {
    imgViewMale.backgroundColor = hexStringToUIColor(hex: "#CBFFE2")
 }

 //Tap Gesture Female
 func femaleGestureTap()
 {
    imgViewFemale.backgroundColor = hexStringToUIColor(hex: "#CBFFE2")
 }

 //Tap Gesture MaleFemale
 func maleFeGestureTap()
 {
    imgViewMaleFe.backgroundColor = hexStringToUIColor(hex: "#CBFFE2")
 }
}

I don't know how can we write a generic method.

2

There are 2 answers

5
Shachar On BEST ANSWER

You could do something like that:

Suppose you have a few objects that you need to attach a tap handler to, assuming they all conform to UIView protocol:

let subviews: [Any] = [label1, label2, label3, view1, imageview1]()
label1.tag = 1 //** add a tag to your object **
for v in subviews {
   self.addTapGesture(to: v)
}

 func tapped(_ sender: UITapGestureRecognizer) {
    print("tapped")
    if sender.view?.tag == 1 {
        // *** this is your label1 view ***
    }
}

func addTapGesture(to: Any?) {
    if let v = to as? UIView {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:)))
        v.addGestureRecognizer(tapGesture)
        v.isUserInteractionEnabled = true
    }
}
4
dahiya_boy On

Define your target selector(tapGestureHandler:) with argument as

let tap = UITapGestureRecognizer(target: self, action: Selector("tapGestureHandler:"))

And check your component like this.

func tapGestureHandler(_ sender: UITapGestureRecognizer) {

     if sender.view is UIView {
     // sender is a UIView 
     }
     else if sender.view is UIImageView{
    // sender is UIimageView
     }
     else{
     // sender is none
     }
}

And be ensure that user interaction is true.