【发布时间】:2018-03-21 09:43:18
【问题描述】:
在我的WalletTableViewController我有两个函数,用来计算Wallet Value:
A. updateCellValue() 被reloadData() 调用,带有tableView 并使用indexPath.row 获取value(价格)和amount(硬币数量)对应于单元格并进行计算以获得该硬币的总价值(amountValue = value * amount)。然后将其与 Core Data 一起保存。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WalletTableViewCell
cell.delegate = self
cell.amountTextField.delegate = self
updateCellValue(cell, atRow: indexPath.row)
return cell
}
func updateCellValue(_ walletTableViewCell: WalletTableViewCell, atRow row: Int) {
var newCryptos : [CryptosMO] = []
var doubleAmount = 0.0
if CoreDataHandler.fetchObject() != nil {
newCryptos = CoreDataHandler.fetchObject()!
}
cryptoPrice = cryptos[row].code!
guard let cryptoDoublePrice = CryptoInfo.cryptoPriceDic[cryptoPrice] else { return }
let selectedAmount = newCryptos[row]
guard let amount = selectedAmount.amount else { return }
var currentAmountValue = selectedAmount.amountValue
doubleAmount = Double(amount)!
let calculation = cryptoDoublePrice * doubleAmount
currentAmountValue = String(calculation)
CoreDataHandler.editObject(editObject: selectedAmount, amount: amount, amountValue: currentAmountValue)
updateWalletValue()
}
B. updateWalletValue() 是一个函数,它获取 Core Data 中的所有 amountValue 对象并将它们加在一起以计算 Wallet Value。
func updateWalletValue() {
var items : [CryptosMO] = []
if CoreDataHandler.fetchObject() != nil {
items = CoreDataHandler.fetchObject()!
}
total = items.reduce(0.0, { $0 + Double($1.amountValue)! } )
WalletTableViewController.staticTotal = total
}
在我的MainViewController 中,Wallet Value 也显示出来了,但是如何刷新它的值呢?
func updateMainVCWalletLabel() {
//... what can I do here??
}
这对WalletViewController 非常有效 当然可以使用TableView 和indexPath,但是我怎样才能从MainViewController 调用updateCellValue 以保持价值更新了吗?
WalletViewController 被实例化并从MainViewController 推送:
@IBAction func walletButtonTapped(_ sender: Any) {
let walletViewController = self.storyboard?.instantiateViewController(withIdentifier: "walletTableViewController")
self.present(walletViewController!, animated: true)
}
【问题讨论】:
-
您可以为此使用
Notification。观察您想要更新值的通知,并在数据发生更改时触发它。 -
请勿转发问题。改进你的问题。例如添加两个视图控制器如何相关的信息
-
@vadian 这是我昨天想问的,但似乎没有人明白,我认为我的问题太糟糕了,我会问一个新的
-
@TheTiger 我更精确地更新了我的问题
-
@martin 是的!你试过
Notification吗?
标签: ios swift function uitableview core-data