以编程方式在 UICollectionViewCell SWIFT 中添加多个按钮 + 接收 touchUpInside 事件 [英] Adding multiple buttons + receiving touchUpInside event inside UICollectionViewCell SWIFT programmatically

查看:36
本文介绍了以编程方式在 UICollectionViewCell SWIFT 中添加多个按钮 + 接收 touchUpInside 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a CollectionView for a list all programmatically in Swift without using Storyboard. I was able to add a tap gesture event to the cell.

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

However, When I added a set of buttons to the UICollectionViewCell's contentView, the buttons do not receive any touch events.

内部控制器

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 内部

Inside 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 是否适合接受不止一种类型的点击操作(点击整个单元格而不是单元格内的多个按钮)?

Is CollectionViewCell suited to accept more than one type of tap action (tapping on the whole cell versus multiple buttons inside cell)?

这是我目前尝试过的:

  1. 在 CollectionView 上禁用点击手势,仍然没有接收事件
  2. 没有向按钮添加点击事件,我试图在单元格内找到点击的位置",然后检查这是否在按钮的范围内,如果是,则触发一个事件.当我尝试添加动画或滚动时,我发现这项工作有问题.

感谢您的建议和帮助.

推荐答案

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

You can set the gesture recognizer to not block the touches in subview

gestureRecognizer.cancelsTouchesInView = false

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

You can also implement UIGestureRecognizerDelegate and set yourself as delegate. Then you can implement shouldReceiveTouch

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

如果您不想对单元格手势识别器中的触摸做出反应,您可以在那里检查哪个视图是目标视图并返回 false.

There you can check which view is targeted and return false if you don't want to react to the touch in the cells gesture recognizer.

这篇关于以编程方式在 UICollectionViewCell SWIFT 中添加多个按钮 + 接收 touchUpInside 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆