【问题标题】:didSelectRowAtIndexpath not triggered for button inside a tableview cell Swift iOS表格视图单元格Swift iOS中的按钮未触发didSelectRowAtIndexpath
【发布时间】:2017-02-27 00:32:03
【问题描述】:

我在表格视图单元格中有一个按钮(如下图所示),当我单击该按钮时,

didSelectRowAt 索引路径

没有被触发,有人可以建议我怎么做吗?

请注意: 我正在执行一组单击按钮的操作,此外我还想要

didselectRowAt indexPath

被触发。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 print("Table view cell has been clicked")   
}

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

当您在单元格中有多个视图时,它们可能会收到触摸事件而不是“单元格”,因此不会触发 didSelectRowAt。在这种情况下,将view.isUserInteractionEnabled = false 添加到每个视图、标签或按钮。

【讨论】:

    【解决方案2】:

    将插座放在自定义单元格类中的按钮上。然后在 cellForItemAt 中设置标签并为按钮添加选择器。这个例子是为了collectionView,只是为了适应tableView。

    如果您想要每个单元格中的按钮,您必须这样做。向单个单元格添加静态按钮不会调用 didSelectItemAt,因为您点击的按钮没有引用可重用单元格 indexPath。

    通过这种方式,我们将 button.tag 发送到函数,以便我们知道按钮与哪个单元格相关。

    class MyClassViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
        .... // Stuff
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        ....// Create Cell
    
        cell.deleteCellButton.tag = indexPath.item
        cell.deleteCellButton.addTarget(self, action: #selector(MyClassViewController.deleteCellButtonTapped(_:)), for: .touchUpInside)
        return cell
    }
    
    func deleteCellButtonTapped(_ sender: Any) {
    
         ... // Stuff
    
          print("Selector called")
    }
    }
    

    【讨论】:

    • 不要使用索引路径作为标签。它在很多情况下都会失败。
    • 我读到苹果不想让你再使用它了。那有什么解决办法呢?因为这似乎是大多数人构建嵌套表视图/集合视图的方式?
    • 这方面的问题很多,所以我不会提供太多细节。但基本上,如果你需要在按钮的action方法中确定一个按钮的索引路径,你可以使用UITableView类的方法,根据按钮相对于table view的frame来计算。
    • @WanderingScouse,@rmaddy,我知道你可以将一个函数附加到一个按钮,如上所示,但是你如何激活像didSelectRowAt indexPath这样的委托方法
    • @user44776 你没有。只需让按钮处理程序和委托方法都调用一个通用方法。
    【解决方案3】:

    如果您在 UITableViewCell 上添加按钮或手势,则 didselectRowAt indexPath 未调用。您可以在剩余的 UI UITableViewCell 上添加按钮,而不是在按钮上应用清除颜色。用户没有显示按钮,您可以执行didselectRowAt indexPath 方法任务。如果您想在按钮方法代码中使用indexpath,请在下面给出。

     func btnChildDropDown(sender:UIButton)
        {
           let cell = sender.superview?.superview as! ChildAgeTableViewCell
           let indexPath = self.tblViewAddRooms.indexPath(for: cell)
    
        }
    

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 2018-09-22
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2016-12-27
      相关资源
      最近更新 更多