swift - 当 CustomCell 标签值更改时如何更新 UITableView?

标签 swift uitableview

我有一个自定义单元格类,其中有两个按钮和一个在其自己的类中定义的标签。当按下按钮时,我使用协议(protocol)委托(delegate)来更新标签的值。但我无法弄清楚如何更新 UITableView。

protocol customCellDelegate: class {
    func didTapDecrementBtn(_ sender: AllCountersTableViewCell)
    func didTapIncrementBtn(_ sender: AllCountersTableViewCell)
    func updateTableViewCell(_ sender: AllCountersTableViewCell)
}

class AllCountersTableViewCell: UITableViewCell {


    @IBOutlet weak var counterValueLbl: UILabel!
    @IBOutlet weak var counterNameLbl: UILabel!
    @IBOutlet weak var counterResetDateLbl: UILabel!

    @IBOutlet weak var counterDecrementBtn: UIButton!
    @IBOutlet weak var counterIncrementBtn: UIButton!

    weak var delegate: customCellDelegate?

    @IBAction func decrementBtnPressed(_ sender: UIButton) {
        delegate?.didTapDecrementBtn(self)
        delegate?.updateTableViewCell(self)
    }

    @IBAction func incrementBtnPressed(_ sender: UIButton) {
        delegate?.didTapIncrementBtn(self)
        delegate?.updateTableViewCell(self)
    }

在我的 ViewController 中,我提供了委托(delegate)。但 reloadData() 不起作用,因此尽管 sender.counterLbl.value 正在更改,但它没有反射(reflect)在 View 上。

extension AllCountersVC: customCellDelegate {

    func didTapIncrementBtn(_ sender: AllCountersTableViewCell) {
        guard let tappedCellIndexPath = tableView.indexPath(for: sender) else {return}
        let rowNoOfCustomCell = tappedCellIndexPath[1]
        let newValue = String(allCounter[rowNoOfCustomCell].incrementCounterValue(by: allCounter[rowNoOfCustomCell].counterIncrementValue))
        sender.counterValueLbl.text = newValue
    }

    func updateTableViewCell(_ sender: AllCountersTableViewCell) {
        allCountersTableView.reloadData()
    }

最佳答案

cellForRow中,您必须设置cell.delegate = self此逻辑才能开始工作。仅仅让您的 Controller 符合您的自定义单元委托(delegate)协议(protocol)是不够的。从您的帖子中,我假设单元格中的 delegate 始终为 nil,这就是它不起作用的原因。

关于swift - 当 CustomCell 标签值更改时如何更新 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388550/

相关文章:

ios - 数据服务错误未解决

ios - 默认标注填充左侧附件 View 的颜色

ios - 如何使物体 swift 从边缘反弹

uitableview - SearchBar、Custom Cell 和 setCell 方法 : fatal error: unexpectedly found nil while unwrapping an Optional value

ios - 不显示来自解析的数据

ios - 2 UIViewController中的UITableView相互影响

ios - 如何在 SwiftUI 中实现触发 switch case 的左或右 DragGesture() ?

swift - 无法在 while 循环内写入数组 - 下标仅获取

ios - 警告 : Attempt to present <UIAlertController: 0x7facd3946920> on <. ..> 已经呈现(空)

ios - 如何在 UITableViewCell 中创建信息按钮?