Swift开发:cell无法获取ViewModel值,UICollectionView不展示数据
问题根源
- 刷新方法调用错误:你在回调中写的是
self.collectionView.reloadData(),但你实际定义的CollectionView变量名是todayCollectionView,这行代码调用了不存在的属性,不会执行任何刷新操作,所以cell一直使用第一次加载时的nil数据渲染。 - 数据存储逻辑不符合列表需求:你当前ViewModel仅存储了单条
TwentyFourHoursMainScreenWeatherModel数据,但是CollectionView需要渲染3条数据,即使刷新成功也无法展示所有列表项。 - 可选值解包写法不规范:
cellForItemAt中if let temp: String? = String(...)的写法会把非可选的String值包装成可选类型,即使数据存在也可能出现预期外的逻辑问题。
修复方案
1. 修正ViewModel数据存储逻辑
把单条数据存储改为存储整个列表数组:
class TwentyFourHoursViewModel { // MARK: -Properties let twentyFourHoursWeatherService: ITwentyFourHoursWeatherService // 替换为存储数组 var weatherList: [TwentyFourHoursMainScreenWeatherModel] = [] init(twentyFourHoursWeatherService: ITwentyFourHoursWeatherService) { self.twentyFourHoursWeatherService = twentyFourHoursWeatherService } func twentyFourHoursViewDidLoad() { twentyFourHoursWeatherService.getCitiesWeather { [weak self] result in guard let self = self else { return } switch result { case .success(let result): // 遍历接口返回的list生成所有cell需要的数据 self.weatherList = result.list.map { item in TwentyFourHoursMainScreenWeatherModel( twentyFourHoursTime: item.dtTxt, twentyFourHoursIcon: item.weather.first?.icon ?? "sunset", twentyFourHoursTemp: item.main.temp ) } self.twentyFourHoursWeatherDidChange?() case .failure(let error): print(error.localizedDescription) } } } var twentyFourHoursWeatherDidChange: (() -> Void)? }
2. 修正ViewController的刷新调用和数据源逻辑
// 回调中的刷新代码修正变量名 twentyFourHoursViewModel.twentyFourHoursWeatherDidChange = { [weak self] in DispatchQueue.main.async { self?.todayCollectionView.reloadData() // 这里改为你的实际变量名 print("闭包中取值: \(self?.twentyFourHoursViewModel.weatherList.first?.twentyFourHoursTemp)") } } // 数据源方法修正 extension MainScrenenViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 改为根据数据条数返回,请求成功前返回0避免空cell return twentyFourHoursViewModel.weatherList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cellTwo = collectionView.dequeueReusableCell(withReuseIdentifier: "todayCell", for: indexPath) as! TwentyFourHoursCollectionViewCell // 解包对应index的数据 let weatherItem = twentyFourHoursViewModel.weatherList[indexPath.row] // 温度转为字符串后赋值,可根据需求调整格式 cellTwo.mainTemperatureLabel.text = String(format: "%.1f", weatherItem.twentyFourHoursTemp) print("cell中取值: \(weatherItem.twentyFourHoursTemp)") return cellTwo } }
内容的提问来源于stack exchange,提问作者Mikl.hart
相关产品推荐
相关产品推荐

