以编程方式在UICollectionViewCell SWIFT中添加多个按钮+接收touchUpInside事件

问题描述:

我想在不使用Storyboard的情况下以编程方式在Swift中以编程方式构建一个CollectionView。我能够将单击手势事件添加到单元格中。以编程方式在UICollectionViewCell SWIFT中添加多个按钮+接收touchUpInside事件

但是,当我向UICollectionViewCell的contentView添加一组按钮时,按钮不会收到任何触摸事件。

内部控制

let sampleCollectionView = UICollectionView(frame: (..), collectionViewLayout: layout) 

//Register the UICollectionViewCell inside UICollectionView 
sampleCollectionView.registerClass(sampleCollectionViewCell.self, forCellWithReuseIdentifier: "sampleCell") 

//Add Tap Gesture event to the cell area 
let tap = UITapGestureRecognizer(target: self, action: "handleTapForCell:") 
sampleCollectionView.addGestureRecognizer(tap) 

func handleTapForCell(recognizer: UITapGestureRecognizer){ 
    //I can break in here 
} 

内CollectionViewCell

class sampleCollectionViewCell: UICollectionViewCell 
{ 

override init(frame: CGRect) { 
    var buttonBack = UIButton(type: .Custom) 
    buttonBack.addTarget(self, action: "actionGoBack:", forControlEvents: UIControlEvents.TouchUpInside) 
    .. 
    self.contentView.addSubview(buttonBack) 
} 

func actionGoBack(sender: UIButton){ 
    //I want to get my touch action break in here when I tap right inside the button but it won't 
}   
} 

是CollectionViewCell适合接受多种类型的龙头作用(对细胞内整个小区与多按键敲击)?

这里是我试过到目前为止:

  1. 停用点手势上的CollectionView,仍然没有收到事件
  2. 无需添加点击事件到按钮,我试图找到里面的水龙头的“位置”单元格,然后检查它是否位于按钮的边界,如果是,则触发一个事件。当我尝试添加动画或滚动时,我发现这项工作变得越来越麻烦。

感谢您的建议和帮助。

+0

你为什么添加一个轻拍识别器到细胞? UICollectionView具有didSelect的回调函数吗? – Moriya

+0

是的,我在单元级别互换了didSelect/tapGesure - 对按钮没有影响。 –

您可以设置手势识别器不会阻止触摸在子视图

gestureRecognizer.cancelsTouchesInView = false 

您还可以实现UIGestureRecognizerDelegate并设置自己作为代表。然后你就可以实现shouldReceiveTouch

optional public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool 

在那里,你可以检查其观点针对性和返回false,如果你不想在细胞手势识别触控反应。

+0

辉煌。只需设置水龙头。 cancelsTouchesInView = false,让事件识别(我必须点击两次)。我现在要做的就是从可再生的东西中找到确切的细胞来处理我的事件。谢谢! –