Add tap gesture to UIStackView

后端 未结 3 2001
轻奢々
轻奢々 2021-02-18 21:49

Im attempting to add a UITapGesture to a UIStackView within a collectionView cell but each time I do my app crashes. (All IBOutlets are co

相关标签:
3条回答
  • 2021-02-18 22:29

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

    cell.fstackView.isUserInteractionEnabled = true 
    
    0 讨论(0)
  • 2021-02-18 22:40

    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)
    }
    
    0 讨论(0)
  • 2021-02-18 22:41

    Set the gesture recognizer in the main thread:

    DispatchQueue.main.async {
        self.view.gestureRecognizers = [self.tapGestureRecognizer]
    }
    
    0 讨论(0)
提交回复
热议问题