3

Codes:

for ... {
   let view = CategoryClass.createMyClassView()
   view.myLabel.text = packTitle
   view.twoLabel.text = packText
   view.bgCaategory.layer.cornerRadius = 30

   i = i + 1
   if(i == 1){
      selectPackId = packId!;
      view.imgSelect.image = UIImage(named: "selected")
   } else {
      view.imgSelect.image = UIImage(named: "select")
   }

   view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSendData(sender:))))

   self.stackView.addArrangedSubview(view)
}

@objc func handleSendData(sender: UITapGestureRecognizer) {
   print("H 1")
}

If i click on view, nothing print "H 1"

I want if i click on view, get id or another value of view

salari mameri
  • 228
  • 5
  • 13

3 Answers3

4

If adding isUserInteractionEnabled as suggested by Marcel still doesn't work, also make sure that every parent view in the hierarchy has a valid frame (you can check it in Debug View Hierarchy).

E.g. it happened to me to add a UIStackView into a parent UIView but the layout constraints were not correct, so I ended up having the parent UIView frame size as 0 (but the UIStackView was still visible).

Eugenio
  • 324
  • 1
  • 5
  • 15
2

If you create the UIStackView in interface builder, the isUserInteractionEnabled property is false by default. This means that the view and all it's child views won't respond to user interaction.

When you create a view in code, this property is true be default.

Add:

stackView.isUserInteractionEnabled = true

You only have to add this once, in your viewDidLoad for example.

Marcel
  • 6,393
  • 1
  • 30
  • 44
-1

The reason it doesn’t work is possibly a wrong method signature. The correct signature for recognizer actions is this:

recognizerAction(_ recognizer: UIGestureRecognizer)
Tom E
  • 1,530
  • 9
  • 17
  • Can you explain more ? – salari mameri May 29 '18 at 07:39
  • Instead of `@objc func handleSendData(sender: UITapGestureRecognizer)` use this: `@objc func handleSendData(_ sender: UITapGestureRecognizer)` and change the call to this: `#selector(handleSendData(_:))`. Not sure, though, if it will solve your problem, but at least this is what a gesture recognizer expects. – Tom E May 29 '18 at 07:51