首页 > 解决方案 > 循环 json 数据并将数据添加到 textLabel

问题描述

我正在尝试获取所有返回的 json 数据并将其内容添加到集合视图中,其中每个索引位置的内容都添加到集合中自己的单元格中,但是,只创建了 1 个单元格,即数组中的第一个索引

这就是它现在的样子

这是我执行请求以获取数据的地方

func fetchSectorData(){
        guard let url = URL(string: "https://financialmodelingprep.com/api/v3/stock/sectors-performance?apikey=\(Api.key)") else {
            fatalError("wrong sector endpoint")
        }
            
        let dataTask = session.dataTask(with: url) { (data, _, error) in
            if error != nil {
                print(error!)
                return
            }
            if let payload = data {
                guard let sectorInfo = try? JSONDecoder().decode(SectorData.self, from: payload) else {
                    print("problem decoding data")
                    return
                }
                self.sectorArray.append(sectorInfo)
            }
            DispatchQueue.main.async {
                self.collectionview.reloadData()
            }
        }
        dataTask.resume()
    }
}

这是我的collectionView,我在其中循环数据并将其附加到单元格,但是只附加了一条数据

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "scrollId", for: indexPath) as! SectorCollectionCell
    
        let sectorPayload = sectorArray[indexPath.row].sectorPerformance
        
        for data in sectorPayload {
            cell.sectorName.text = data.sector
            cell.performance.text = data.changesPercentage
        }

        
        return cell
    }

这是我试图取回的数据

{
  "sectorPerformance" : [ {
    "sector" : "Aerospace & Defense",
    "changesPercentage" : "0.0241%"
  }, {
    "sector" : "Airlines",
    "changesPercentage" : "-2.0008%"
  }, {
    "sector" : "Auto Components",
    "changesPercentage" : "0.4420%"
  }, {
    "sector" : "Automobiles",
    "changesPercentage" : "-0.7118%"
  }, {
    "sector" : "Banking",
    "changesPercentage" : "-0.1773%"
  } ]
}

标签: arraysswiftuicollectionview

解决方案


在此循环中,您每次都覆盖sectorNameand标签。performance因此,标签仅显示sectorPayload.

for data in sectorPayload {
    cell.sectorName.text = data.sector             // overwrites every loop iteration 
    cell.performance.text = data.changesPercentage // overwrites every loop iteration
}

要解决这个问题,这取决于你想做什么。您可以将所有值附加到一个字符串并让标签显示附加的字符串。

for data in sectorPayload {
    cell.sectorName.text = cell.sectorName.text + " \(data.sector)"
    cell.performance.text = data.changesPercentage + " \(data.sector)"
}

或者,您可能希望生成更多单元格,每个单元格都位于每个sectorPayload. 然后每个部分中的单元格将显示 adata.sectordata.changesPercentagea 内sectorPayload


推荐阅读