首页 > 解决方案 > 如何获取集合视图动态行数?

问题描述

我正在从 API 收集数据

示例 API - 这有不同的省和卫生区

    {
        "summary": [
            {
                "cases": 520,
                "cumulative_cases": 63244,
                "cumulative_deaths": 614.0,
                "date": "11-04-2021",
                "deaths": 0.0,
                "health_region": "Calgary",
                "province": "Alberta"
            },
            {
                "cases": 139,
                "cumulative_cases": 12660,
                "cumulative_deaths": 123.0,
                "date": "11-04-2021",
                "deaths": 0.0,
                "health_region": "Central",
                "province": "Alberta"
            } 
   ]
}

**收藏查看代码**

//首先,我试图计算行数。我不确定我的方法是对还是错

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            
            var count: Int = 0
            for text in 1...100{
                if jsonData?.summary[text].province == dataFromSelection {
                    count = jsonData?.summary.count ?? 0
                    print("count block")
                }
            }
            return count
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            
            if collectionView == myCollectionView {
                    print("if block")
                if (dataFromSelection == jsonData?.summary[indexPath.row].province) {
                    print("im here")
                    let today = jsonData?.summary[indexPath.row].cases
                    let tDeaths = jsonData?.summary[indexPath.row].cumulative_deaths
                    let tCases = jsonData?.summary[indexPath.row].cumulative_cases
                    let regionName = jsonData?.summary[indexPath.row].health_region
                    
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RegionCell", for: indexPath) as! RegionCell
                    cell.configure(region: regionName!, totCase: tCases!, todCases: today!, totDeaths: tDeaths!)
                    return cell
                }

模拟器图像

请帮我解决这个问题

标签: iosswiftxcodeuicollectionview

解决方案


首先为摘要详细信息创建数组,然后根据选择的省份过滤您的摘要数组。前任:

让 summaryArray = [ [“病例”:520,“累积病例”:63244,“累积死亡”:614.0,“日期”:“11-04-2021”,“死亡”:0.0,“健康区域”:“卡尔加里”,“省”:“阿尔伯塔”],[“病例”:139,“累积病例”:12660,“累积死亡”:123.0,“日期”:“11-04-2021”,“死亡”:0.0,“健康区域”:“中央”,“省”:“阿尔伯塔”]]

let filterArray = summaryArray.filter({($0["province"] as?String "") == dataFromSelection})

现在使用此filterArray来计算行数并在集合视图单元格中显示详细信息


推荐阅读