我有一个带有 tableView 的 viewController 来显示我的模型列表,但我不知道为什么 reloadData 没有无缘无故地调用 cellForRowAtIndexPath!我在 viewDidload() 中实现了表视图数据源和委托,我确定我的表视图与我的 VC 连接,numberOfRowsInSection 也返回正确的值
这是我的代码:
protocol UserListDisplayLogic: AnyObject {
func displayUserList(viewModel: FetchUserList.ViewModel)
}
class UserListViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet weak var tableView: UITableView!
// MARK: Properties
var interactor: UserListBusinessLogic?
var router: UserListRouting?
var userList: [DisplayedUserListProtocol]?
// MARK: LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
interactor?.getUserList()
}
// MARK: SetUp View
private func setUpView() {
setUpTableView()
}
private func setUpTableView() {
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
tableView.register(UINib(nibName: userListTableViewCell, bundle: nil), forCellReuseIdentifier: userListTableViewCell)
}
}
// MARK: TableViewDelegate && TableViewDataSource
extension UserListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userList?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: userListTableViewCell, for: indexPath) as! UserListTableViewCell
cell.config(viewModel: userList?[indexPath.row])
return cell
}
}
// MARK: UserListDisplayLogic
extension UserListViewController: UserListDisplayLogic {
func displayUserList(viewModel: FetchUserList.ViewModel) {
userList = viewModel.displayedUserList
tableView.reloadData()
}
}
cellForRowAt 方法未被调用的问题可能与空的 userList 或缺少的 userList 对象有关
在 numberOfRowsInSection 方法中,您返回 userList?.count ?? 0. ??如果 userList 为 nil,运算符提供默认值 0,因此如果 userList 为空或 nil,numberOfRowsInSection 方法将返回 0。
如果 userList 为空或 nil,则不会调用 cellForRowAt 方法,因为没有要显示的行。要确认这是否是问题所在,您可以在 numberOfRowsInSection 方法中添加一条打印语句,以检查该方法是否实际被调用以及 userList?.count 的值是否符合您的预期:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection called with count: \(userList?.count ?? 0)")
return userList?.count ?? 0
}
如果 userList?.count 的值为 0 或 nil,那么在调用 UserListDisplayLogic 扩展的 displayUserList 方法中的 tableView.reloadData() 之前,您需要确保 userList 属性已正确填充数据。
更新
如果正在调用 cellForRowAt 方法但单元格未正确显示,则在“cell.config(viewModel: userList?[indexPath.row])”行上设置断点并使用 View Debugger 可以帮助识别任何问题电池设计。
要使用 View Debugger,您可以按照以下步骤操作:
更新
另一种可能性是 tableView 没有在主线程上重新加载。您可以尝试将 reloadData() 方法调用包装在 DispatchQueue.main.async 块中,以确保它在主线程上被调用,如下所示:
DispatchQueue.main.async {
self.tableView.reloadData()
}