gpt4 book ai didi

ios - tableView 中按钮的 addTarget

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:42 24 4
gpt4 key购买 nike

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

我正在尝试添加目标,但它什么也没做。我需要将行索引传递给 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)
}

我也试过从#selector 中删除 (sender:),但它不会改变功能。

最佳答案

为了在 View Controller 中处理按钮回调,您有两种选择:

目标行动:

像您所做的那样在 cellForRow 方法中添加目标操作。您的代码可能无法正常工作,因为您在按钮应该可见时隐藏了按钮,不是吗?

我想你需要更换这个

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

有了这个:

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

你应该每次都更新标签,因为单元格在 tableView 中被重用,如果不是每次调用 cellForRow 时都这样做,你可能很容易遇到这样的情况调用了一个回调,但它的标签属于上一个单元格使用中的 indexPath。此外,我已将 isHidden 逻辑更改为相反的逻辑。我猜你应该在 isOfflineAvailable 返回 true 时隐藏按钮,对吧?

委托(delegate)模式

它在 SO 和许多其他网站上被描述了一百万次。基本上,您定义一个单元格协议(protocol),在您的 Controller 中实现它,并在按下按钮时将回调从单元格发送到它的委托(delegate)。您可以在 my answer 中找到更多详细信息对于类似的问题。

关于ios - tableView 中按钮的 addTarget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com