我有一个 api 调用响应,我将在其中获取两种格式的项目列表。
"items" : [
{
"menu_code" : "NDS",
"name" : "Monday"
},
{
"menu_code" : "NDN",
"name" : "Tuesday"
}
]
格式 2 在这里:
"items" : [
{
"unit" : "Nos",
"name" : "Chapathi\/Pulkas",
"quantity" : 2
},
{
"unit" : "Cup",
"name" : "Palya\/Curry",
"quantity" : 1
}
]
现在我的收藏 View 中有一个标签。因此,基于我标签中的响应,我需要像下面的示例一样显示:
名称 - 数量单位,
名称 - 数量单位,
名称 - 数量单位...等
基于来自响应的计数。
另一种格式:
name - menu_code,
name - menu_code,
name - menu_code ..etc
基于来自响应的计数。
我的模型类:
struct Item : Codable {
let unit : String?
let name : String?
let quantity : Int?
let menuCode : String?
}
我的收藏 View :
var names:[String] = []
var qty:[Int] = []
var unit:[String] = []
var menuCode:[String] = []
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionCell", for: indexPath) as! HomeCollectionCell
cell.productName.text = self.allCategory[indexPath.item].menuName
let itemsData = self.allCategory[indexPath.row].items
print(itemsData)
for dt in itemsData {
// print(dt)
let nam = dt.name
let unt = dt.unit
let mCode = dt.menuCode
let qtys = dt.quantity
names.append(nam ?? "")
unit.append(unt ?? "" )
qty.append(qtys ?? 0)
menuCode.append(mCode ?? "" )
// cell.ProductsubLabel.text = itemsData
}
return cell
}
所以我创建了一个数组,但不确定如何附加到标签。而且我也不知道要区分这两种格式并显示在标签中。对此有任何帮助。
提前致谢!
更新:
第三种新格式:
"items" : [
{
"unit" : "Nos",
"product_name" : "Chapathi\/Pulkas",
"quantity" : 2
},
{
"unit" : "Cup",
"product_name" : "Palya\/Curry",
"quantity" : 1
}
]
最佳答案
一个非常有效的解决方案是在返回适当数据的结构中添加一个description
属性。如果 unit
不存在,则返回 menuCode
信息,否则返回 quantity
和 unit
struct Item : Codable {
let unit : String?
let name : String?
let productName : String?
let quantity : Int?
let menuCode : String?
var description : String {
let name = self.name ?? self.productName ?? "n/a"
if unit == nil {
return "\(name) - \(menuCode!)"
} else {
return "\(name) - \(quantity!) \(unit!)"
}
}
}
在 cellForItemAt
中,将 items
映射到它们的描述,并通过逗号加入数组。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionCell", for: indexPath) as! HomeCollectionCell
let category = self.allCategory[indexPath.item]
cell.productName.text = category.menuName
let itemsData = category.items
let subData = itemsData.map {$0.description}.joined(separator: ", ")
cell.ProductsubLabel.text = subData
print(subData)
return cell
}
并删除 cellForItemAt
上面的四个丑陋的数组
关于ios - 需要根据来自响应的格式显示标签中的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54168051/