简体   繁体   中英

Add tap gesture to UIStackView

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)
    }

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

cell.fstackView.isUserInteractionEnabled = true 

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)
}

Set the gesture recognizer in the main thread:

DispatchQueue.main.async {
    self.view.gestureRecognizers = [self.tapGestureRecognizer]
}

I had UIButtons as subviews, so even if I added gesture to UIStackView, it ignored my gesture.

So I added the code

button.isUserInteractionEnabled = false

to make UIStackView receive my touch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM