Swift - 在表格视图单元格内单击按钮不会调用该单元格的 did select row 函数

问题描述 投票:0回答:4

我以编程方式创建一个表格视图,每个表格视图单元格都有与其关联的按钮。

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

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

问题是,如果我直接单击表格视图单元格中的按钮,则选择的行不会被调用,并且不会给出标签值。为此,我必须先单击单元格,然后单击按钮才能知道与该行关联的标签。

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

上面是单元格的正常外观,下面显示了如何选择单元格才能获取索引值。

swift uitableview uibutton tableview didselectrowatindexpath
4个回答
2
投票

按钮操作不会调用

didSelectRowAt
。你应该使用 delegate 方法。如果不知道委托意味着参考这个


1
投票

单元格的按钮不会触发

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
,而是您需要向按钮添加
target
,这通常在
cellForItemAt
内完成。

将目标添加到单元格内的按钮

   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)
    }

处理按钮操作

@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
}

0
投票

禁用按钮的控制对我有用。

以编程方式:

editButton.isEnabled = false

~或者~

IB:

取消选中“控制”部分中的“已启用”框。


0
投票

禁用按钮的用户交互控制控件对我有用。

以编程方式:

editButton.isUserInteractionEnabled = false

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.