我测试了收集视图可以显示的内容。但是,我无法在集合视图中检索和添加数组结果。
这是我的代码:
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath) as! MainPageCollectionViewCell
cell.FoodTitle.text = arr[indexPath.row].title
cell.Food.image = arr[indexPath.row].image_url
return cell
}
关于数组,它是fetchFoodList内部的函数。
func fetchFoodList(){
let url = URL(string: "MYAPI.json")
guard let unwrappedUrl = url else { return }
let task = URLSession.shared.dataTask(with: unwrappedUrl,completionHandler: {(data,response,error)in
if error != nil{
print(error!)
} else {
if let urlContent = data{
do {
let json = try JSON(data:data!)
let recipes = json["recipes"]
for arr in recipes.arrayValue{
print(arr["title"])
print(arr["image_url"])
}
}
catch{
print("JSON Processing Failed")
}
}
}
})
task.resume()
}
}
但是,数组结果标题和image_url可以显示在控制台中。