如何在UICollection补充视图中使用UIButton?

我试图在UICollectionView补充视图(页脚)中放置一个UIButton。 我已经将使用故事板的UIButton连接到UICollectionViewCell的子类,并可以通过编程方式更改其属性,包括背景图像。 但是,当我把button的内部事件连接到一个方法时,它不会触发。 事实上,该button甚至没有看起来对用户的触摸有视觉响应。 在解决问题时,我试图添加一个UIButton到集合视图的头部,并看到相同的行为。 将button添加到不相关的视图会在按下时产生交互效果。

在UICollection补充视图中,我需要做些什么来实现UIButton?

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

无论如何,如果button没有响应,首先要做的是检查它的所有祖先视图的userInteractionEnabled设置为YES 。 一旦button在屏幕上,在debugging器中暂停并执行以下操作:

 (lldb) po [[UIApp keyWindow] recursiveDescription] 

find列表中的button并复制其地址。 然后你可以检查它和每个超级视图。 例:

 (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 。 窗口的超级视图是零。

我有一个自定义的button,它的子类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将触发.TouchUpInside ,并按下时,控件将在视觉上突出显示。