You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift开发:cell无法获取ViewModel值,UICollectionView不展示数据

问题根源

  1. 刷新方法调用错误:你在回调中写的是 self.collectionView.reloadData(),但你实际定义的CollectionView变量名是 todayCollectionView,这行代码调用了不存在的属性,不会执行任何刷新操作,所以cell一直使用第一次加载时的nil数据渲染。
  2. 数据存储逻辑不符合列表需求:你当前ViewModel仅存储了单条TwentyFourHoursMainScreenWeatherModel数据,但是CollectionView需要渲染3条数据,即使刷新成功也无法展示所有列表项。
  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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:06:06