Search code examples
swiftuitapgesturerecognizerstackview

Swift: addGestureRecognizer not work for stackview children


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


Solution

  • 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.