在我的Swift代码中,我有一个带有3个按钮的UICollectionViewCell
(所有三个都有IBActions)。从我UICollectionViewController
我现在想要"赶上"单个按钮点击。
我已经关注了这个StackOverflow question,我可以在我的CollectionViewController里面找到UICollectionViewCell的修饰,并将此行添加到viewDidLoad
gestureRecognizer.cancelsTouchesInView = false
并使用此功能
func handleTapForCell(recognizer: UITapGestureRecognizer){
//I can break in here
}
但现在丢失的部分是如何判断出哪三个按钮被点击?我在按钮上设置了不同的标签,但我没有在gestureRecognizer上找到处理这些标签的任何地方。
有什么想法吗?
答案 0 :(得分:1)
您可以遵循协议/委托范例。
您需要做的是在自定义单元格中定义协议。然后使viewcontroller订阅单元委托。
在自定义单元类中实现IBActions。在按钮的IBActions中调用委托方法。委托单元格的viewcontroller将接收单元格内按钮点击的回调。
答案 1 :(得分:1)
我认为,你不需要在单元格上添加Gesture来获取tableviewCell的按钮动作。此代码可以帮助您:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Your tableviewCell code here
//set tag of cell button
cell.button1.tag = 1
cell.button2.tag = 2
cell.button3.tag = 3
//add action of your cell button
cell.button1.addTarget(self, action: Selector("cellButtonTapped:event:"), forControlEvents: .TouchUpInside)
cell.button2.addTarget(self, action: Selector("cellButtonTapped:event:"), forControlEvents: .TouchUpInside)
cell.button3.addTarget(self, action: Selector("cellButtonTapped:event:"), forControlEvents: .TouchUpInside)
// return cell
}
func cellButtonTapped(sender:UIButton, event:AnyObject){
let touches: NSSet = event.allTouches()!
let touch = touches.anyObject()
let currentTouchPosition: CGPoint = (touch?.locationInView(YOUR_TABLEVIEW_INSTANCE))!
if let indexPath: NSIndexPath = self.YOUR_TABLEVIEW_INSTANCE.indexPathForRowAtPoint(currentTouchPosition)!{
if sender.tag == 1{
//cell first button tap
}else sender.tag == 2{
//cell second button tap
}
else sender.tag == 3{
//cell 3rd button tap
}
}
}