Swift – 在加载另一个单元格后更新单元格中的标签?

有人能告诉我如何实现以下目标吗?

我有2个细胞:

  1. 我的第一个单元格已加载并包含label

  2. 我的第二个单元格已加载并包含另一个label 。 该标签使用URLSession的值填充。

我想要做的是,使用单元格2 label的值更新单元格1中的label

我不太清楚该怎么做。 我已经尝试在tableview中创建一个变量来捕获结果并执行didSet然后tableView.reloadData ,但是这会陷入无限循环并失败。

我可以发布代码,但是我所描述的并没有什么独特之处,所以只会在被问到时添加代码。 提前致谢!

根据要求,下面的代码。 我希望runningTotal的值在更新后进入我的infoCell.totalPriceLabel.text

 var runningTotal: Double = Double() override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if cellItems.count == 0 { let orderEmptyCell = Bundle.main.loadNibNamed("OrderEmptyTableViewCell", owner: self, options: nil)?.first as! OrderEmptyTableViewCell return orderEmptyCell } else { if indexPath.section == 0 { let infoCell = Bundle.main.loadNibNamed("InfoTableViewCell", owner: self, options: nil)?.first as! InfoTableViewCell infoCell.totalPriceLabel.text = String(Double(runningTotal)) print(runningTotal) return infoCell }else if indexPath.section == 1 { let item: BasketModel = cellItems[indexPath.row] as! BasketModel let ordersCell = Bundle.main.loadNibNamed("OrderTableViewCell", owner: self, options: nil)?.first as! OrderTableViewCell if item.multi == 1 { ordersCell.nameLabel.text = item.name! + ": " + item.filling! } else { ordersCell.nameLabel.text = item.name! } ordersCell.priceLabel.text = String(Double(basketStruct.getQty(id: item.id!)) * Double(item.price!)!) runningTotal += (Double(basketStruct.getQty(id: item.id!)) * Double(item.price!)!) ordersCell.quantityLabel.text = String(basketStruct.getQty(id: item.id!)) return ordersCell } } } 

这个问题不是一个特别难以解决的问题,因此我将尝试将其分解为一小部分。 从你所描述的,你大致是在正确的方向。

首先,您需要一些方法来跟踪第一个单元格。 您可能希望从表视图中使用tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)委托方法以获取第一个单元格,然后将其保存到该视图控制器中的变量中,类似于var firstCell: MyCustomCellClass?

然后,在第二个单元格中使用didSet的想法,我们可以使用委托来通知视图控制器任何更改。 为此,我将在第二个单元类中声明一个协议:

 protocol MySecondCellProtocol { func myValueDidChange(newValue: String) } 

然后在你的第二个单元类中,你将需要一个委托变量: var delegate: MySecondCellProtocol? 这样你就可以做到以下几点:

 var myValue = "" { didSet(newVal) { delegate?.myValueDidChange(newVal) } } 

在视图控制器中,您需要扩展自己以实现此协议:

 extension MyViewController: MySecondCellProtocol { func myValueDidChange(newValue: String) { firstCell?.label.text = newValue } } 

您还需要返回tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)函数并设置:

 cell2.delegate = self 

为了接收代表电话。

如果有任何不清楚的地方,请告诉我。 我显然没有包含执行此操作所需的所有代码,因为它将取决于您的方案,并且到目前为止没有看到您的代码库,这是我能做的一样好。