ios - 当表视图范围内的值更新时,更新表视图范围之外的值
问题描述
我在视图控制器中放置了一个标签,当 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 中的标签
解决方案
你有两个不同的引用对象(你的视图控制器和你的单元类),所以你需要使用一个协议在两个对象之间进行通信。这是一个例子:
//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,除非它是静态类对象,如单例)。
推荐阅读
- reactjs - useEffect 依赖数组和 ESLint 穷举-deps 规则
- python - 在 docker 外部使用 docker 入口点和文件
- electron - 在浏览器和渲染器进程中使用系统代理
- oracle - Oracle 数据泵导出忽略表
- android - 重新打开应用程序的问题
- asp.net-core - asp-for="" 中的“动态”数据
- r - 当我从 R 中的现有数据集创建随机样本时,为什么会得到重复数据?
- reactjs - material-ui 按钮活动样式
- android - 具有水平 GridLayoutManager 的 RecyclerView 将其高度调整为最大行
- javascript - JS:按多个字段对数组进行排序不起作用