我是Swift / Xcode的新手,在更新TableView单元格数据时遇到问题。我似乎也无法从任何类似的StackOverflow问题中找到/实现这一简单问题的答案。
我有一个应用程序,一旦按下按钮,计时器就会每1秒开始api调用一次API,但问题是,当从所有带有viewDidLoad()
的数组中加载所有tableview数据时,标签中显然没有数据可显示因为尚未打过电话。
一旦按下按钮,数据便开始流动,但标签中什么也没有出现。我相信这是因为标签需要在每次调用时进行更新才能显示新数据。
基本上我想做的是打电话给
cell.cellLabelTwo.attributedText = tableData[indexPath.row].secondRowLabel
cell.cellLabelTwo.font = UIFont(name: "Helvetica Neue", size: 19)
cell.cellLabelTwo.textAlignment = .right
从下面显示的代码中,每次进行新的api调用。
struct MyData {
var imageRow: UIImage
var firstRowLabel: String
var secondRowLabel: NSAttributedString
}
var tableData: [MyData] = []
override func viewDidLoad() {
super.viewDidLoad()
tableData = [
MyData(imageRow: UIImage(named: "ada.png")!, firstRowLabel: "ADA/USDT", secondRowLabel: adaPercentGainString.htmlToAttributedString!)
]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "protoCellOne") as! TableViewCell
cell.cellImageOne.image = tableData[indexPath.row].imageRow
cell.cellLabelOne.text = tableData[indexPath.row].firstRowLabel
cell.cellLabelTwo.attributedText = tableData[indexPath.row].secondRowLabel
cell.cellLabelTwo.font = UIFont(name: "Helvetica Neue", size: 19)
cell.cellLabelTwo.textAlignment = .right
return cell
}
您只需要在每次API调用后重新加载表视图。
tableView.reloadData()
最好在API调用的完成处理程序中调用它,但不要在调用API的地方提供代码。
重新加载数据将为每个单元格调用委托方法cellForRowAt:
,这是您要运行代码的位置。