arrays - 循环 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%"
} ]
}
解决方案
在此循环中,您每次都覆盖sectorName
and标签。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.sector
和data.changesPercentage
a 内sectorPayload
。
推荐阅读
- python - 如何将对象转换为日期时间索引
- python - 有没有其他方法可以找到具有低开销和高精度的记录之间的相似性度量(除了 Jaro-Winkler 算法)?
- android - 为多设备支持扩展 gradle 任务
- python - 从python中的列表元素中删除字符
- java - 检查不重复的随机数
- android - 用于相机的具有透明度的矩形框
- mysql - MySQL 复制在 Master 上具有 NULL-able 列,在 Slave 上具有 NOT NULL
- rspec - Rails 5 Api 中的 rspec 控制器测试仍然很常见吗?
- python - Jupyter Notebook 不会输出
- python - 通过 id 计算从基线的变化