【问题标题】:Figure out which of multiple buttons in UICollectionView cell was tapped找出 UICollectionView 单元格中的多个按钮中的哪个被点击
【发布时间】:2016-07-08 12:15:21
【问题描述】:

在我的 Swift 代码中,我有一个带有 3 个按钮的 UICollectionViewCell(三个按钮都有 IBActions)。从我的UICollectionViewController 我现在想“捕捉”单个按钮的点击。

我已经关注了这个StackOverflow question,我可以在我的 CollectionViewController 中捕捉 UICollectionViewCell 的修饰,并将这一行添加到 viewDidLoad

gestureRecognizer.cancelsTouchesInView = false

还有这个功能

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

但现在缺少的部分是我怎样才能确定三个按钮中的哪一个被点击了?我在按钮上设置了不同的标签,但在gestureRecognizer上没有找到处理这些标签的地方。

有什么想法吗?

【问题讨论】:

  • 那么您想检测从handleTapForCell 中点击了哪个子视图?如果是,这里是客观的 C 答案,应该对您有所帮助。 stackoverflow.com/questions/38225747/…
  • 但是为什么要使用 Tap 手势而不是按钮的 IBAction?

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

我认为,您无需在单元格上添加手势即可获得 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
            }
        }
    }

【讨论】:

  • 这对我有用。超酷。谢谢。以防万一有人想在 Swift 2 中使用它:我已经更新了选择器行 cell.button1.addTarget(self, action: #selector(MyViewController.buttonTapped(_:event:")), forControlEvents: .TouchUpInside) 并在 CollectionView 中更改 indexPathForRowAt 点为 if let indexPath: NSIndexPath = self.collectionView.indexPathForItemAtPoint(currentTouchPosition)!{
【解决方案2】:

您可以遵循协议/委托范例。

您需要做的是在自定义单元格中定义一个协议。然后让视图控制器订阅单元委托。

在自定义单元类中实现 IBActions。在按钮的 IBActions 中调用委托方法。为单元格委派的视图控制器将接收单元格内的按钮点击回调。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2012-08-14
    • 2021-02-24
    • 2011-11-22
    相关资源
    最近更新 更多