在我的WalletTableViewController
中,我有两个函数,用于计算钱包值(value)
:
A. updateCellValue()
由 reloadData()
使用 tableView
调用并使用 indexPath.row
获取cell对应的value
(价格)和amount
(币数),并计算得到总值那枚硬币(金额值 = 值(value) * 金额)。然后将其与核心数据一起保存。
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
对象并将它们加在一起计算钱包值(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)
}
最佳答案
如果您想在多个 View Controller 中使用一个方法,您应该实现该方法,以便您可以从任何地方调用该方法。例如,您可以在此处使用单例类。
- 创建一个 swift 文件并根据需要命名(例如 WalletHelper 或 WalletManager)
- 然后你会得到一个如下格式的文件
class WalletHelper: NSObject
{
}
- 为该类创建一个共享实例
static let shared = WalletHelper()
- 实现你想要的方法
func getWalletValue() -> Float {
// write your code to get wallet value`
// and return the calculated value
}
- 最后像这样调用那个方法
let walletValue = WalletHelper.shared. getWalletValue()
WalletHelper.swift 看起来像
import UIKit
class WalletHelper: NSObject
{
static let shared = WalletHelper()
func getWalletValue() -> Float {
// write your code to get wallet value
// and return the calculated value
}
}
关于ios - 在另一个 View 中使用需要 UITableView 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49402848/