Add tap gesture to UIStackView

19,081

Solution 1

Is the stackview enabled for touch ? Try to set Userinteraction Parameter

cell.fstackView.isUserInteractionEnabled = true 

Solution 2

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

If you are accessing the stack view property in the collection view cell subclass's init or in the collection view's delegate methods, the stack view may not have been initialized yet. 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)
}

Solution 3

Set the gesture recognizer in the main thread:

DispatchQueue.main.async {
    self.view.gestureRecognizers = [self.tapGestureRecognizer]
}
Share:
19,081

Related videos on Youtube

Terrance
Author by

Terrance

Updated on October 22, 2022

Comments

  • Terrance
    Terrance over 1 year

    Im attempting to add a UITapGesture to a UIStackView within a collectionView cell but each time I do my app crashes. (All IBOutlets are connected) This there something I'm doing wrong here?

     let fGuesture = UITapGestureRecognizer(target: self, action: #selector(self.showF(_:)))
     cell.fstackView.addGestureRecognizer(fGuesture)
    
     func showF(sender: AnyObject){
            print(111)
        }
    
    • Daniel Krom
      Daniel Krom almost 8 years
      at the #selector(self. change self to your class name
    • osxdirk
      osxdirk over 6 years
      Show us, how your crash looks (console output).
    • Jeff Muir
      Jeff Muir over 6 years
      If you are using Swift 4, you need @objc on showF. Also, showF should include a _ for the parameter.
  • raf
    raf almost 4 years
    I would recommend against timing solutions. They are brittle and can break for a number of reasons (newer devices run faster and break timing, new OS versions change the order things, etc). In this case I would recommend using a lifecycle event such as awakeFromNib.