【问题标题】:iOS Swift 3 - UIButton on UIStackView in UICollectionViewCell is not responding to tap events (no interaction)iOS Swift 3 - UICollectionViewCell 中 UIStackView 上的 UIButton 没有响应点击事件(无交互)
【发布时间】:2017-11-25 14:34:24
【问题描述】:

我有一个UICollectionViewCell 子类,上面有一个UIStackView。 StackView 填充了UIButtons,一切看起来都很好 但是按钮是不可点击的。

如果我在 UIScrollView(为了实验)而不是在 stackview 上布局相同的按钮,按钮响应正常,所以似乎是 stackview 的某些东西导致了问题

有什么想法吗?

这是我如何向 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)
    }


 }

【问题讨论】:

  • 禁用stackview交互为stackview.isUserInteractionEnabled = false
  • 为什么?那么它的所有排列视图都不会是可交互的
  • 我认为 stackview 会覆盖按钮的可交互属性。所以,我说过了,你试过了吗?
  • 试过了。没用
  • 下载我的演示应用dropbox.com/s/7j6pyca3i4y13mt/MyDemoApp.zip?dl=0 查看视图控制器“SpotInfoViewController”>>“buttonClicked”

标签: ios iphone uicollectionview uicollectionviewcell uistackview


【解决方案1】:

使用此代码让 UIButton 响应点击事件:

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
}

有用的链接:

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

我也遇到过类似的问题,可以解决。请查看我的帖子,其中我描述了此类原因的情况,并试图解释我是如何解决的。

UIButton is not clickable after first click

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    相关资源
    最近更新 更多