使用协议传递所选行的indexPath

时间:2019-04-05 17:41:01

标签: swift uitableview protocols

我是MVC和协议的新手,但我正在尝试使用协议传递数据来适应MVC。我在tableview单元格上有一个按钮,并且试图获取所选行的indexPath以便在点击该按钮时执行某些操作。我创建了协议,并将委托设置为正确的VC。我的问题是,如何通过委托获取选定的indexPath。原谅我的无知

表格视图单元格

class PlaylistCell: UITableViewCell {

 var playButtonTappedDelegate: PlaylistCelldelegate!

@IBAction func PlayButton(_ sender: Any) {
    // Dont know how to get this Int, when cell is tapped
    playButtonTappedDelegate.handlePlayButton(for: self, for: <#Int#>)
}

}

协议

protocol PlaylistCelldelegate {
func handlePlayButton( for cell: PlaylistCell, for row: Int)

}

我已遵从该VC上的代表

  class PlaylistVC: UIViewController, PlaylistCelldelegate {

    func handlePlayButton(for cell: PlaylistCell, for row: Int) {
        print("row\(row)")
    }

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

        return cell
    }    
}

1 个答案:

答案 0 :(得分:1)

删除委托方法上的for row参数。只需发送单元格。

然后,您可以在indexPath实现中的表格视图中找到单元格的handlePlayButton

func handlePlayButton(for cell: PlaylistCell) {
    let indexPath = tableView.indexPath(for: cell)
}
相关问题