Add click gesture to UIStackView

I am trying to add a UITapGesture to a UIStackView in a collectionView cell, but every time I make an application crash. (All IBOutlets are connected) Is this something I am doing wrong here?

  let fGuesture = UITapGestureRecognizer(target: self, action: #selector(self.showF(_:))) cell.fstackView.addGestureRecognizer(fGuesture) func showF(sender: AnyObject){ print(111) } 
+5
source share
2 answers

- is the stack view turned on for touch? add this if not.

 cell.fstackView.isUserInteractonEnabled = true 
+4
source

If the application crashes due to fatal error: unexpectedly found nil while unwrapping an Optional value - you may need to add some delay before adding a gesture recognizer to the stack view.

If you access the stack view property in a subclass of the collection view cell or in the methods of the collection view delegate, the stack view may not yet be initialized. Try using a timer or GCD to add a 0.1 second delay and it should work fine ...

 Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(prepareStackView), userInfo: nil, repeats: false) 

...

 @objc func prepareStackView() { let tap = UITapGestureRecognizer(target: self, action: #selector(stackViewTapped)) myStackView.addGestureRecognizer(tap) } 
0
source

All Articles