tableView中的按钮addTarget

sph*_*ynx 1 uitableview ios swift swift3

我正在尝试为tableView中的某些项添加下载按钮.我已经创建了自定义单元格类并添加了标签和按钮插座,一切都在显示信息,甚至按钮都显示它应该在哪里.

我正在尝试添加目标,但它什么也没做.我需要将行索引传递给buttonClicked函数,还是应该在自定义单元格类中创建此函数然后执行某些操作?我想知道这方面的最佳做法.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "PlaylistCell", for: indexPath) as! PlaylistTableViewCell

        let playlist = self.playlists?[indexPath.row]

        cell.titleLabel.text = playlist?.getTitle()


        if (playlist?.isOfflineAvailable())! {
            cell.downloadButton.isHidden = false
        } else {
            cell.downloadButton.isHidden = true
            cell.downloadButton.tag = indexPath.row
            cell.downloadButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
        }

        return cell
    }

    func buttonClicked(sender: UIButton) {
        let buttonRow = sender.tag
        print(buttonRow)
    }
Run Code Online (Sandbox Code Playgroud)

我也试过从#selector中删除(sender :),但它没有改变功能.

ale*_*nik 6

要在视图控制器中处理按钮回调,您有两种选择:

目标 - 动作:

cellForRow像你一样在方法中添加target-action .您的代码可能无法正常工作,因为您在隐藏按钮时它应该是可见的,不是吗?

我想你需要更换它

if (playlist?.isOfflineAvailable())! {
    cell.downloadButton.isHidden = false
} else {
    cell.downloadButton.isHidden = true
    cell.downloadButton.tag = indexPath.row
    cell.downloadButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
}
Run Code Online (Sandbox Code Playgroud)

有了这个:

cell.downloadButton.isHidden = playlist?.isOfflineAvailable()
cell.downloadButton.tag = indexPath.row
cell.downloadButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

你应该每次更新标签,因为细胞被重复使用tableView,如果每次cellForRow调用时都不这样做,你可以很容易地得到一个调用回调但是它的标签属于上一个单元用法的indexPath的情况.我也改变isHidden了相反的逻辑.我猜你应该在isOfflineAvailable返回true 时隐藏按钮,对吧?

委托模式

它在SO和许多其他网站上被描述了数百万次.基本上,您定义了一个单元协议,在控制器中实现它,并在按下按钮时从单元格向其委托发送回调.您可以在我的答案中找到类似问题的更多详细信息.