如何用RxSwift将API获取的Zone数组元素逐个显示在TableViewCell中?
解决TableView逐个展示zones数组元素的问题
1. 完善ViewModel的数据管理
确保TimeStampViewModel持有完整的zones数组,并提供获取数组长度和单个元素的方法:
class TimeStampViewModel { private var zones: [Zone] = [] // 从接口获取数据后更新zones数组 func fetchTimeStamps(completion: @escaping () -> Void) { WebService.shared.fetchData { [weak self] timeStamp in self?.zones = timeStamp.zones completion() } } // 返回zones数组的元素数量 func zoneCount() -> Int { return zones.count } // 获取指定位置的Zone模型 func getZone(at index: Int) -> Zone? { guard index >= 0 && index < zones.count else { return nil } return zones[index] } }
2. 配置TableView数据源
在CountryHoursVC中,将ViewModel的zones数组与TableView绑定,确保每个Cell对应数组中的单个元素:
class CountryHoursVC: UIViewController { @IBOutlet weak var tableView: UITableView! private let viewModel = TimeStampViewModel() override func viewDidLoad() { super.viewDidLoad() setupTableView() loadData() } private func setupTableView() { tableView.register(UINib(nibName: "CountryHourTableViewCell", bundle: nil), forCellReuseIdentifier: "CountryHourCell") tableView.dataSource = self } private func loadData() { viewModel.fetchTimeStamps { [weak self] in DispatchQueue.main.async { self?.tableView.reloadData() } } } } extension CountryHoursVC: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.zoneCount() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "CountryHourCell", for: indexPath) as? CountryHourTableViewCell, let zone = viewModel.getZone(at: indexPath.row) else { return UITableViewCell() } cell.zone = zone return cell } }
3. 修正Cell的UI绑定逻辑
在CountryHourTableViewCell中,通过单个Zone模型的didSet方法更新UI,避免直接操作整个数组:
class CountryHourTableViewCell: UITableViewCell { @IBOutlet weak var countryNameLabel: UILabel! @IBOutlet weak var timeStampLabel: UILabel! var zone: Zone? { didSet { guard let zone = zone else { return } countryNameLabel.text = zone.countryName timeStampLabel.text = zone.timestamp } } }
关键注意事项
- 禁止在Cell中持有整个
zones数组,必须通过数据源方法给每个Cell传递单个Zone模型 - 确保
numberOfRowsInSection返回zones数组的实际长度,保证TableView创建对应数量的Cell - 接口数据更新后,必须在主线程调用
tableView.reloadData()刷新界面
内容的提问来源于stack exchange,提问作者agestis
相关产品推荐
相关产品推荐

