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

标签 ios swift uicollectionview uicollectionviewcell

我正在尝试在 Swift 中以编程方式构建一个列表的 CollectionView,而不使用 Storyboard。我能够向单元格添加点击手势事件。

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

内部 Controller

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. 在没有向按钮添加点击事件的情况下,我试图找到单元格内点击的“位置”,然后检查这是否在按钮的范围内,如果是,则触发一个事件。当我尝试添加动画或滚动时,我发现这个解决方法有问题。

感谢您的建议和帮助。

最佳答案

您可以将手势识别器设置为不阻止 subview 中的触摸

gestureRecognizer.cancelsTouchesInView = false

您还可以实现 UIGestureRecognizerDelegate 并将自己设置为委托(delegate)。然后就可以实现shouldReceiveTouch

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

在那里,您可以检查哪个 View 是目标 View ,如果您不想对单元格手势识别器中的触摸使用react,则返回 false。

关于ios - 添加多个按钮 + 以编程方式在 UICollectionViewCell SWIFT 内接收 touchUpInside 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33338842/

相关文章:

ios - UICollectionView becomeFirstResponder 错误行为

ios - 使用 Objective-C block 编写完成处理程序

arrays - 反向枚举过滤掉数组中的相似对象

ios - 在 UICollectionView 滚动后获取可见项的更新 IndexPath

ios - 删除对象后重新加载 CollectionViewController?

ios - 重新加载数据后未调用 UICollectionView 数据源方法

ios - 从 Storyboard 设置时看不到 UIImageView 图像

ios - 浏览器中的 HTML5 可以在 iOS 锁屏上连续播放音频吗?

ios - "Cannot assign to"遍历结构数组时出错

swift - 改变 View 的大小并移动周围的 View