【问题标题】:How can I use a UIButton in a UICollection supplementary view?如何在 UICollection 补充视图中使用 UIButton?
【发布时间】:2012-11-26 19:47:04
【问题描述】:

我正在尝试将 UIButton 放置在 UICollectionView 补充视图(页脚)中。我已经使用故事板将 UIButton 连接到 UICollectionViewCell 的子类,并且可以以编程方式更改它的属性,包括背景图像。但是,当我将按钮的 touch up inside 事件连接到一个方法时,它不会触发。事实上,按钮甚至看起来都没有对用户的触摸做出视觉响应。在故障排除中,我尝试将 UIButton 添加到集合视图的标题中并查看相同的行为。将按钮添加到不相关的视图中会在按下时产生交互效果。

在 UICollection 补充视图中实现 UIButton 需要做一些特别的事情吗?

【问题讨论】:

    标签: objective-c ios cocoa-touch ios6 uicollectionview


    【解决方案1】:

    补充视图应该是UICollectionReusableView(或其子类),而不是UICollectionViewCell

    无论如何,如果按钮没有响应,首先要做的是检查其所有祖先视图是否将userInteractionEnabled 设置为YES。一旦按钮出现在屏幕上,在调试器中暂停并执行以下操作:

    (lldb) po [[UIApp keyWindow] recursiveDescription]
    

    在列表中找到按钮并复制其地址。然后你可以检查它和每个superview。示例:

    (lldb) p (BOOL)[0xa2e4800 isUserInteractionEnabled]
    (BOOL) $4 = YES
    (lldb) p (BOOL)[[0xa2e4800 superview] isUserInteractionEnabled]
    (BOOL) $5 = YES
    (lldb) p (BOOL)[[[0xa2e4800 superview] superview] isUserInteractionEnabled]
    (BOOL) $6 = YES
    (lldb) p (BOOL)[[[[0xa2e4800 superview] superview] superview] isUserInteractionEnabled]
    (BOOL) $8 = YES
    (lldb) p (BOOL)[[[[[0xa2e4800 superview] superview] superview] superview] isUserInteractionEnabled]
    (BOOL) $9 = YES
    (lldb) p (BOOL)[[[[[[0xa2e4800 superview] superview] superview] superview] superview] isUserInteractionEnabled]
    (BOOL) $10 = NO
    (lldb) po [[[[[0xa2e4800 superview] superview] superview] superview] superview]
    (id) $11 = 0x00000000 <nil>
    

    在这里,我发现直到根目录(UIWindow)的所有视图都从isUserInteractionEnabled 返回YES。窗口的 superview 为 nil。

    【讨论】:

    • @robmayhoff:问题在于我对错误的父级进行了子类化。感谢您收看这个!
    • @markdorison 哈哈,有意思。我真的没想到会是这个问题。
    • @robmayhoff:当我做出一个改变并且它奏效时,我和你一样感到惊讶!
    【解决方案2】:

    我有一个自定义按钮,它继承了UIControl 并将其放在UICollectionReusableView 中。为了使它工作,我使控件的每个子视图及其子视图的子视图不处理用户交互。

    func disableUserInteractionInView(view: UIView) {
        view.userInteractionEnabled = false
        for view in view.subviews {
            self.disableUserInteractionInView(view)
        }
    }
    
    // My control has a subview called contentView which serves as a container
    // of all my custom button's subviews.
    self.disableUserInteractionInView(self.contentView)
    

    自从添加该代码后,.TouchUpInside 的所有事件侦听器都会触发,并且当按下时控件会在视觉上突出显示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      相关资源
      最近更新 更多