ios - UITableViewCell 中的按钮在重新加载后不会保持与初始 Cell 的连接

标签 ios iphone swift xcode uitableview

我在自定义单元格中有一个按钮,它在按下后更改图像,但每当触发重新加载时,新添加的单元格都会更改图像而不是旧图像。这是我的 cellForRowAt:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Sender", for: indexPath) as! Sender
        cell.clearCellData()
        cell.message.text = self.items[indexPath.row].content
        cell.name.text = self.items[indexPath.row].name
        cell.from = self.items[indexPath.row].fromID
        return cell
    }

按钮的 outlet 和 action 都在 Button 单元格中,如下所示:

@IBAction func downVoted(_ sender: Any) {
    if(self.downVote.image(for: .normal) == #imageLiteral(resourceName: "DownGray")){
        self.downVote.setImage(#imageLiteral(resourceName: "DownOn"), for: .normal)
    }else{
        self.downVote.setImage(#imageLiteral(resourceName: "DownGray"), for: .normal)
    }
}

在添加新行之前它工作正常。我尝试将按钮标签设置为与单元格标签相同,但没有帮助。有谁知道解决这个问题?

谢谢。

最佳答案

这可能是因为单元格被重用了,尝试在 cellForRowAt: 中设置图像这样做你需要在你的模型中有一个 bool 值(选择或不选择),你必须使用委托(delegate)touch ,并在您的 Controller 中实现它,这样您就可以在索引处更改模型并重新加载 TableView ,我提供了示例代码

protocol SenderDelegate {
    func downVoteTapped(_ cell: MainTVCell)
}

class Sender: UITableViewCell {
   @IBAction func downVoted(_ sender: Any) {
      delegate!.downVoteTapped(self)
   }
}

和 Controller

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Sender", for: indexPath) as! Sender
        cell.clearCellData()
        cell.delegate = self
        cell.message.text = self.items[indexPath.row].content
        cell.name.text = self.items[indexPath.row].name
        cell.from = self.items[indexPath.row].fromID
        if self.items[indexPath.row].selected == true {
           self.downVote.setImage(#imageLiteral(resourceName: "DownOn"), for: .normal)
        } else {
            self.downVote.setImage(#imageLiteral(resourceName: "DownGray"), for: .normal)
        }
        return cell
    }

func downVoteTapped(_ cell: Sender) {
    let index = tableView.indexPathForCell(cell)?.row)!
    self.items[index].selected == !self.items[index].selected 
    tableView.reloadData()
}

并且不要忘记执行 SomeViewController: SenderDelegate 在你的模型中 var selected = false

关于ios - UITableViewCell 中的按钮在重新加载后不会保持与初始 Cell 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44546273/

相关文章:

iphone - 不想点击两次以使用 sharekit 应用程序在 Facebook 中分享消息?

ios - 只要几个文本字段为空,就禁用按钮

iOS 8 无法连接到 BLE。可以连接到 iOS 9

ios - 在已经在其他地方分配/初始化之后,如何从 XIB 重新加载 View ?

iphone - 单独使用 UINavigationViewController

ios - 确定数组中的最小值并在另一个数组中找到对应的字符串

objective-c - 从 Objective C 转换为 Swift 时的预期声明

ios - VoiceOver 读取表格标题两次并始终添加单词 "heading"

ios - 在 Swift 中向自定义按钮添加闭包

ios - 在 ios 7.1 中自定义按钮形状