简体   繁体   中英

iOS Swift 3 - UIButton on UIStackView in UICollectionViewCell is not responding to tap events (no interaction)

I have a UICollectionViewCell subclass which has a UIStackView on it. The StackView is populated with UIButtons and everything looks fine however the buttons are untappable.

If I layout the same buttons on a UIScrollView (for the sake of experiment) instead of on a stackview, the buttons respond fine so it seems like something with the stackview is causing the issue

Any ideas?

我的布局

Here is the code of how I add buttons to the StackView

 func prepareStackView(buttonsArray: Array<UIButton>) {


    var rect:CGRect = (stackView?.frame)!
    rect.size.width = btn.frame.size.width * buttonsArray.count
    stackView?.frame = rect //The frame of the stackview is set as such so that it looks exactly like I want


    //Add all the buttons
    for btn in buttonsArray {
            //The buttons already have their selectors set
            stackView?.addArrangedSubview(btn)
    }


 }

Use this code for UIButton to respond to click event:

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {

    if clipsToBounds || isHidden || alpha == 0 {
        return nil
    }

    for subview in subviews.reversed() {
        let subPoint = subview.convert(point, from: self)
        if let result = subview.hitTest(subPoint, with: event) {
            return result
        }
    }

    return nil
}

Helpful link:

Capturing touches on a subview outside the frame of its superview using hitTest:withEvent:

I have also encountered similar problem and able to resolve. Please check my post where I have described the scenario of this type of cause and tried to explain how I was able to resolve.

UIButton is not clickable after first click

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