首页 > 解决方案 > 当表视图范围内的值更新时,更新表视图范围之外的值

问题描述

我在视图控制器中放置了一个标签,当 tableview 内的标签值发生更改时,我想在 tableview 外部的标签上显示该值我已将值存储在单元格类的 var 中并更新但是标签没有更新,请帮忙。

表格视图单元格中的按钮操作

@IBAction func addButton(_ sender: Any) {
    count += 1
    totalAmount = ItemAmount * Double(count)
    totalCharge += ItemAmount
}
@IBAction func minusButton(_ sender: Any) {
    if count > 0{
        count -= 1
        totalAmount = ItemAmount * Double(count)
        totalCharge -= ItemAmount
    }
}

我已将 totalCharge 声明为 public 并在视图控制器中访问它并将值赋予 cellforRowat 中的标签

标签: iosswiftuitableview

解决方案


你有两个不同的引用对象(你的视图控制器和你的单元类),所以你需要使用一个协议在两个对象之间进行通信。这是一个例子:

//define the protocol
protocol updateLabelsDelegate {
 func updateLabels(itemAmount: Double)
}

//Add the delegate to your cell class
class customCell: UITableViewCell {

 var delegate: updateLabelsDelegate?

 @IBAction func addButton(_ sender: Any) {
    count += 1
    totalAmount = itemAmount * Double(count)
    totalCharge += itemAmount
    delegate.updateLabels(itemAmount: itemAmount)
 }
 @IBAction func minusButton(_ sender: Any) {
    if count > 0{
        count -= 1
        totalAmount = itemAmount * Double(count)
        totalCharge -= itemAmount
        delegate.updateLabels(itemAmount: itemAmount)
    }
 }
}

//Conform to the protocol in your view controller
extension ViewController: updateLabelsDelegate {
 func updateLabels(itemAmount: itemAmount) {
 //... take the itemAmount value passed here and use it to update your label on the view controller
 }
}

最后一件事,对 itemAmount 使用适当的大小写(不是 ItemAmount,除非它是静态类对象,如单例)。


推荐阅读