我试图将UIButton放在UICollectionView补充视图(页脚)中。我已经使用故事板将UIButton连接到UICollectionViewCell的子类,并且可以以编程方式更改它的属性,包括背景图像。但是,当我将按钮事件内部的触摸连接到方法时,它不会触发。事实上,该按钮甚至看起来没有在视觉上响应用户的触摸。在疑难解答中,我尝试将UIButton添加到集合视图的标题中,并查看相同的行为。将按钮添加到不相关的视图会在按下时产生交互效果。
在UICollection补充视图中实现UIButton需要做些什么特别的事情吗?
答案 0 :(得分:19)
补充视图应该是UICollectionReusableView
(或其子类),而不是UICollectionViewCell
。
无论如何,如果按钮没有响应,首先要检查其所有祖先视图是否已将userInteractionEnabled
设置为YES
。按钮在屏幕上时,在调试器中暂停并执行以下操作:
(lldb) po [[UIApp keyWindow] recursiveDescription]
找到列表中的按钮并复制其地址。然后你可以检查它和每个超级视图。例如:
(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
)都会从YES
返回isUserInteractionEnabled
。窗口的超级视图是零。
答案 1 :(得分:0)
我有一个自定义按钮,其子类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
的所有事件侦听器都将触发,并且控件将在按下时直观地突出显示。