我是 Swift/Xcode 新手,在更新 TableView 单元格数据时遇到问题。我似乎也无法从任何类似的 StackOverflow 问题中找到/实现这个简单问题的答案。
我有一个应用程序,一旦按下按钮,它就会开始在计时器上每 1 秒进行一次 api 调用,但问题是,当使用 viewDidLoad()
从数组加载所有 tableview 数据时,有显然标签中没有可显示的数据,因为尚未进行任何调用。
一旦我按下按钮,数据就开始流动,但标签中没有显示任何内容。我相信这是因为每次调用时都需要更新标签才能显示新数据。
数据也是来自 HTML 的 NSAttributedString。不确定这是否相关,因为它似乎在表格 View 之外的测试单元中工作正常。
本质上我想做的是以某种方式调用
cell.cellLabelTwo.attributedText = tableData[indexPath.row].secondRowLabel
每次进行新的 api 调用时,都使用下面所示的代码,并使用新的增益百分比数据更新 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 ,我还将 TableView 分配给 View Controller 的数据源和委托(delegate)。对于许多其他人来说,添加 IB socket 似乎是解决此问题的方法,但它仍然没有在电池标签中显示任何内容...
最佳答案
您只需在每次 API 调用后重新加载表格 View 即可。
tableView.reloadData()
最好在 API 调用的完成处理程序中调用此方法,但您无需在调用 API 的位置提供代码。
重新加载数据将调用每个单元格的委托(delegate)方法cellForRowAt:
,这是您要运行的代码的位置。
关于ios - 更新 TableView 单元格数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58779285/