Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add tap gesture to UIStackView

Tags:

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)     } 
like image 334
Terrance Avatar asked May 12 '16 17:05

Terrance


People also ask

What is UITapGestureRecognizer Swift?

UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer . For gesture recognition, the specified number of fingers must tap the view a specified number of times. Although taps are discrete gestures, they're discrete for each state of the gesture recognizer.


2 Answers

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

cell.fstackView.isUserInteractionEnabled = true  
like image 53
Fadi Avatar answered Sep 22 '22 04:09

Fadi


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) } 
like image 24
Thomas Jeans Avatar answered Sep 25 '22 04:09

Thomas Jeans