首页 文章

Swift - tableview单元格内的单击按钮不会在该单元格的功能上调用did选择行

提问于
浏览
1

我以编程方式创建了一个tableview,每个tableview单元格都有与之关联的按钮 .

如果我单击该行,我可以计算出与该行上的按钮相关联的标签,然后在应用其他功能时能够编辑 Headers .

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    TmpActionConnectorTag = indexPath.row + 700 //Tag associated to button
}

单击该按钮时,我有此代码更改该行上的另一个按钮

let tag = TmpActionConnectorTag
    let tmpButton = self.view.viewWithTag(tag) as? UIButton

问题是,如果我直接点击tableview单元格中的按钮,则确定的选择行不会被调用,也不会给出标记值 . 要做到这一点,我必须先在单元格内单击然后按钮才能知道与该行关联的标记 .

单击按钮时有没有办法锻炼索引行,所以我不必单击实际的单元格?

上面是单元格正常显示的方式,下面显示了如何选择单元格以获取索引值 .

2 回答

  • 0

    按钮操作不会调用 didSelectRowAt . 你应该去 delegate 方法 . 如果不了解委托意味着refer this

  • 1

    单元格的按钮不会触发 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 而是需要在按钮上添加 target ,这通常在 cellForItemAt 内完成 .

    Add target to button within cell

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = MyTableViewCell()
            cell.button.tag = indexPath.row
            cell.button.addTarget(self, action: #selector(didTapCellButton(sender:)), for: .touchUpInside)
        }
    

    Handle button action

    @objc func didTapCellButton(sender: UIButton) {
        guard viewModels.indices.contains(sender.tag) else { return } // check element exist in tableview datasource
    
        //Configure selected button or update model
    }
    

相关问题