Swift 3:如何在表格视图的多个部分中使用操作按钮?

时间:2016-09-26 14:13:20

标签: ios swift uitableview uibutton swift3

我想在每个部分的每一行中单击一个按钮时运行一个独特的功能。 例如,问题是,如果我在3个部分中有3行,并且在按下按钮时配置第一行以运行函数,则所有3个部分的第一行运行相同的功能。我正在尝试为不同部分中的所有行运行独特的函数。

这是我的tableView代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: languageID, for: indexPath) as! LanguageTableViewCell

    switch indexPath.row {
    case 0:
        cell.phraseLBL.text = "description 1"
        cell.playBtn.tag = indexPath.row
        cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay), for: .touchUpInside)

    case 1:
        cell.phraseLBL.text = "description 2"
        cell.playBtn.tag = indexPath.row
        cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay), for: .touchUpInside)

    case 2:
        cell.phraseLBL.text = "description 3"
        cell.playBtn.tag = indexPath.row
        cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay), for: .touchUpInside)
    default:
        break
    }

    return cell
}

这是IBAction的{​​{1}}:

Button

2 个答案:

答案 0 :(得分:3)

你可以这样做

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: languageID, for: indexPath) as! LanguageTableViewCell

    switch indexPath.row {
    case 0:
        cell.phraseLBL.text = "description 1"


    case 1:
        cell.phraseLBL.text = "description 2"

    case 2:
        cell.phraseLBL.text = "description 3"

    default:
        break
    }

    cell.playBtn.tag = indexPath.row
    cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay(_:)), for: .touchUpInside)


    return cell
}

并将方法调用为

@IBAction func pressPlay(_ sender: UIButton){

    let touchPoint = sender.convert(CGPoint.zero, to:maintable)
    // maintable --> replace your tableview name

    let clickedButtonIndexPath = mainTable(forRowAtPoint: touchPoint)



}

答案 1 :(得分:0)

您可以为每个单元格设置索引路径而不是标记。 IndexPath由section和row组成。通过检查按钮所属的哪个部分和哪一行,您可以唯一地识别正确的功能。

相关问题