我正试图从JSON的UICollectionview中获取每餐的部分。我就是不能这样做
{
"meals" : [
{
"id" : 279,
"unit" : "حبة",
"disable" : "0",
"created_at" : "2017-03-06 19:17:23",
"time" : "فوري",
"small" : "0",
"type" : "2",
"desc" : "",
"price" : "6",
"image" : "a4f730f447e753a995e342e12446ab1958bdb5c3136b6.jpg",
"family_id" : "115",
"updated_at" : "2017-03-06 19:17:23",
"deleted_at" : null,
"medium" : "0",
"large" : "0",
"name" : "ساندوتش فلافل كعك بالسمسم "
},
{
"id" : 280,
"unit" : "حبة",
"disable" : "0",
"created_at" : "2017-03-06 19:21:51",
"time" : "فوري",
"small" : "0",
"type" : "2",
"desc" : "",
"price" : "5",
"image" : "1c65581aa774203a4335bc6d93fe2b6358bdb6f3edb23.jpg",
"family_id" : "115",
"updated_at" : "2017-03-06 19:22:27",
"deleted_at" : null,
"medium" : "0",
"large" : "0",
"name" : "سندويش فلافل عربي اصناف "
},
type
是用餐的部分名称。每餐都会有一个1,2,3,4的部分
现在我按如下方式设置UICollectionview的行:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if meals.count > 0 {
self.collectionView.backgroundView = nil
return meals.count
}
let rect = CGRect(x: 0,
y: 0,
width: self.collectionView.bounds.size.width,
height: self.collectionView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: rect)
noDataLabel.text = "تقدر تطلب اي شي من \(nameOfShop.text!)"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = NSTextAlignment.center
self.collectionView.backgroundView = noDataLabel
return 0
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mealsCell", for: indexPath) as! MealCollectionViewCell
let entry = meals[indexPath.row]
cell.mealName.text = entry.meal_name
cell.mealPrice.text = "\(entry.price) ريال"
cell.mealImage.hnk_setImage(from: URL(string: entry.Logo))
return cell
}
以下是我从API获取数据的方法
let name = subJson["name"].stringValue
let price = subJson["price"].stringValue
let logo = subJson["image"].stringValue
let id = subJson["id"].stringValue
let logoString = "http://app.com/upload/img/\(logo)"
let info = Meals(meal_id: id, Logo: logoString, meal_name: name, price: price)
self.meals.append(info)
对不起,我想我应该解释更长的密码。
答案 0 :(得分:1)
使用数组数组为dataSource建模。而不是self.meals.append(info)
,将meals
初始化为数组数组,然后:
let type = subJson["type"].intValue
self.meals[type-1].append(info) // note here that you may need to adjust depending on the possible values of type.
然后在collectionView(_:numberOfItemsInSection:)
:
if meals[section].count > 0 {
etc...
}
在numberOfSections(in:)
:
return meals.count
在collectionView(_:cellForItemAt:)
:
let entry = meals[indexPath.section][indexPath.row]
或者,如果type
不是连续的整数列表,Dictionary
可能是存储meals
的更好方式:
var meals = Dictionary<String, Array<Meals>>()
for type in types {
meals[type] = []
}
...
self.meals[type] = info
这样您就不必担心开始使用正确数量的数组,如果JSON响应中缺少一个type
值,它仍然可以工作。然后需要更改UITableView
dataSource方法以将节号映射到您的类型键。