我的目标是:
我有一个 getData
类,用于从服务器下载数据,然后将其保存到数组中。之后,我希望类 getData
能够更新 HomeViewController
中的 cellTableView
。
如果我将所有 func
都放在一个 swift 文件中,它就可以工作。但我想多次使用它,不要在每个 UIViewController
中使用相同的代码,我还想了解如何使用委托(delegate)。
我试过使用 this类似问题的答案。
问题:
目前代码下载和存储但不更新 cellTableView
。
HomeViewController:
import UIKit
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, GetDataDelegate {
let getData = GetData()
...
override func viewDidLoad() {
super.viewDidLoad()
cellTableView.delegate = self
cellTableView.dataSource = self
cellTableView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "homeCell")
for (n, _) in MyVariables.coinTickerArray.enumerated() {
MyVariables.dataArray.append(HomeLabel(coinNameCell: MyVariables.coinNameArray[n], tickerCell: MyVariables.coinTickerArray[n]))
}
getData.storeData()
}
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let coinCell = tableView.dequeueReusableCell(withIdentifier: "homeCell", for: indexPath) as! HomeCell
...
return coinCell
}
...
@IBAction func refreshButtonPressed(_ sender: UIBarButtonItem) {
getData.storeData()
self.didFinishGetData(finished: true)
}
@IBAction func currencyControlPressed(_ sender: UISegmentedControl) {
...
getData.storeData()
}
}
获取数据:
import UIKit
import Alamofire
import SwiftyJSON
class GetData {
var delegate: GetDataDelegate?
func downloadData(url: String, number: Int) {
...
}
func updateCoinData(json: JSON, number: Int) {
...
self.delegate?.didFinishGetData(finished: true)
}
func storeData () {
for (n, _) in MyVariables.coinTickerArray.enumerated() {
MyVariables.finalURL = MyVariables.baseURL+MyVariables.coinTickerArray[n]+MyVariables.currentCurency
downloadData(url: MyVariables.finalURL, number: n)
}
}
}
View+GetDataDelegate:
import Foundation
extension HomeViewController: GetDataDelegate {
func didFinishGetData(finished: Bool) {
guard finished else {
// Handle the unfinished state
return
}
self.cellTableView.reloadData()
}
}
获取数据委托(delegate):
import Foundation
protocol GetDataDelegate {
func didFinishGetData(finished: Bool)
}
最佳答案
我无法从您发布的代码中判断 cellTableView 的声明位置。我相信 cellTableView 的每个实例都应该替换为 tableView。您在 dataSource 和委托(delegate)方法中调用 tableView,但随后使用 cellTableView 重新加载数据。
您还应该更多地研究委派。最初是一个很难理解的概念,但一旦你理解了它,这样的任务就会变得轻而易举。
关于ios - 从 Swift 中的另一个类刷新 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889185/