我在使用表中的 reloadData() 时遇到问题。 我已经设置了表格和单元格,并添加了表格,甚至为单元格创建了一个单独的类以防出现问题。 我只是无法将任何数据加载到表中......我已经阅读了这里和其他网站上的问题,但没有一个解决方案能给我解决方案...... 我看到它也是一个错误,但它在不同的项目中工作,所以它不是我的 Xcode 版本。 我已经尝试在 cellForRowAt 内部的 viewDidLoad 中加载,并且还使用 Dispatch 将其放在函数内部和外部的主线程上。我也绝望地尝试了一个按钮,但仍然没有运气。这是我的代码,如果您发现我遗漏的任何内容,请感谢您的帮助。
//
// VCRoster.swift
// MC
//
// Created by James McAdam on 08/07/2018.
// Copyright © 2018 James McAdam. All rights reserved.
//
import UIKit
class VCRoster: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableViewData: [Roster] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = rosterTable.dequeueReusableCell(withIdentifier: "rosterCell") as? rosterCell
cell!.dateLbl.text = tableViewData[indexPath.row].date
//Have also tried ? with the cell
cell!.messageLbl.text = tableViewData[indexPath.row].message
tableView.reloadData()
return cell!
}
@IBOutlet weak var rosterTable: UITableView!
@IBAction func load(_ sender: UIBarButtonItem) {
self.rosterTable.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// dispatchMain().async {
// self.rosterTable.reloadData()
// }
// self.rosterTable.reloadData()
getDataFromServer(for: "Bx7faf08A9fYJ7bZCNMUX9EzxYN2") { (result) in
// Check our result
switch result {
case .success(let results):
// print("Done")
self.tableViewData = results.data
//self.tablewView.reloadData()
//self.rosterTable.reloadData()
// print(results)
case .failure(let message):
// print("Error")
print(message)
}
}
}
}
最佳答案
首先从不,从不,从不在cellForRow
中调用reloadData()
- 确保 TableView 的数据源(和委托(delegate))连接到 Interface Builder 中的 View Controller
- 删除
cellForRow
中的tableView.reloadData()
- 在
viewDidLoad
的完成处理程序中的主线程上调用reloadData()
override func viewDidLoad() {
super.viewDidLoad()
getDataFromServer(for: "Bx7faf08A9fYJ7bZCNMUX9EzxYN2") { (result) in
// Check our result
switch result {
case .success(let results):
self.tableViewData = results.data
DispatchQueue.main.async {
self.rosterTable.reloadData()
}
case .failure(let message):
print(message)
}
}
}
关于Swift: tableView.reloadData() 表中没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51248745/