[英]addTarget for button in tableView
我正在尝试为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)
}
我也尝试过从#selector中删除(sender :),但它不会更改功能。
为了在视图控制器中处理按钮回调,您有两种选择:
目标动作:
就像您一样,在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)
}
有了这个:
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时隐藏按钮,对吧?
委托模式
在SO和许多其他站点上,它被百万次描述。 基本上,您定义了一个单元协议,在您的控制器中实现该协议,并在每按一次按钮时将回调从单元发送到其委托。 您可以在我的类似问题答案中找到更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.