表格视图单元格按钮,单击后更改按钮图像



目前我的项目有一个表格视图控制器,每行都有一个按钮和文本。单击按钮后,我在弄清楚如何更改特定行上的按钮图像时遇到了问题。我已经有函数"override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath(",将我的应用程序带到一个新视图。我需要按钮(单击时(将特定行上的数据添加到收藏夹变量中。然后将显示在不同的屏幕上。我的按钮不会更改视图。

目前我有一个按钮事件函数,每次单击一行中的按钮时都会调用该函数。我遇到的问题是我不知道如何访问单击的行中的特定按钮,而只更改该按钮的图像。

这是我的代码:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
// Setting Text and images
cell.batchName.text = processes[indexPath.item].batch_name
cell.startTime.text = processes[indexPath.item].starttime
cell.endTime.text = processes[indexPath.item].endtime
cell.slaTime.text = processes[indexPath.item].SLA
var statusColor = UIColor.black
// Calling Button event function
cell.starButton.addTarget(self, action: #selector(favoriteStarClicked), for: UIControlEvents.touchUpInside)
return cell
}
@IBAction func favoriteStarClicked(_ sender: Any) {
// Need to change the image of the button that was clicked 
}

现代 Swift 方式是回调闭包

  • 在模型中为收藏夹状态添加属性

    var isFavorite = false
    
  • 在界面生成器中,选择自定义单元格中的按钮,然后按⌥⌘4转到属性检查器。在弹出式菜单中State Config选择Selected,然后在Image弹出窗口中选择star图像(将状态Default图像留空(。

  • 在自定义单元格中,为按钮添加callback属性和操作(将其连接到按钮(。图像通过按钮的isSelected属性进行设置

    var callback : (()->())?
    @IBAction func push(_ sender: UIButton) {
    callback?()
    }
    
  • cellForRow根据isFavorite设置图像并添加回调

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
    // Setting Text and images
    cell.batchName.text = processes[indexPath.item].batch_name
    cell.startTime.text = processes[indexPath.item].starttime
    cell.endTime.text = processes[indexPath.item].endtime
    cell.slaTime.text = processes[indexPath.item].SLA
    var statusColor = UIColor.black
    let item = processes[indexPath.row]
    cell.button.isSelected = item.isFavorite
    cell.callback = {
    item.isFavorite = !item.isFavorite
    cell.button.isSelected = item.isFavorite
    }
    return cell
    }
    

回调更新单元格中的模型和图像


  • 没有协议/委托。
  • 没有自定义目标/操作。
  • 没有标记。
  • 没有索引路径。
  • 没有单元格框架数学。

最新更新