更新TableView单元格数据



我是Swift/Xcode的新手,在更新TableView单元格数据时遇到了问题。我似乎也无法从任何类似的StackOverflow问题中找到/实现这个简单问题的答案。

我有一个应用程序,一旦按下按钮,它就会开始每隔1秒在计时器上调用一次api,但问题是,当所有表视图数据都从带有viewDidLoad()的数组中加载时,显然没有数据显示在标签中,因为还没有进行调用。

一旦我按下按钮,数据就会开始流动,但标签中什么都没有显示。我相信这是因为标签需要在每次调用时更新,以便显示新数据。

该数据也是HTML中的NSAttributedString。但不确定这是否相关,因为它在表视图之外的测试单元中似乎工作得很好。

本质上,我想做的是以某种方式调用

cell.cellLabelTwo.attributedText = tableData[indexPath.row].secondRowLabel

从下面显示的代码中,每次进行新的api调用时,使用新的%gain数据更新cellLabelTwo。

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
}

编辑:我已经添加了@IBOutlet var tableView: UITableView!并将其连接到View Controller,我还将表视图分配给了View Controller的数据源和委托。对于许多其他人来说,添加IB插座似乎是解决这个问题的办法,但它仍然没有在细胞标签中显示任何内容。。。

您只需要在每次API调用后重新加载表视图。

tableView.reloadData()

这最好在API调用的完成处理程序中调用,但不能在调用API的地方提供代码。

重新加载数据将为每个单元格调用委托方法cellForRowAt:,这是您要运行的代码所在的位置。

相关内容

最新更新