gpt4 book ai didi

ios - 使用数组项属性值显示在 UITableView/UICollectionView 中

转载 作者:行者123 更新时间:2023-11-28 11:16:02 24 4
gpt4 key购买 nike

我知道如何使用数组在 UItableViewUICollectionView 中显示,但不确定如何指定数据。

因此,不是简单地显示数组中的所有项目,而是使用项目属性值来过滤结果。例如,数组中的每个项目都有一个名为数字的属性,如果数字为 2,则显示 products[indexPath.row].number == 2 如果 .number == 1 然后不要。

在我的应用程序中,我有一个获取请求,我创建了一个数组以显示在 collectionView 中。每个 Product 都有一个名为 number 的属性,但是如何显示 number 等于 2 的产品?

获取请求:

var products = [Product]()

func loadData() {

var error: NSError?

let moc1 = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let request1 = NSFetchRequest(entityName: "Product")
request1.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
self.products = moc1?.executeFetchRequest(request1, error: &error) as! [Product]

self.collectionView.reloadData()
}

Collection View :

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return products.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell

cell.textLabel?.text = self.products[indexPath.row].title

return cell

}

最佳答案

那么,假设您有一系列产品:

let products =  [
[ "name" : "t-shirt", "number" : 3 ],
[ "name" : "shirt", "number" : 1 ],
[ "name" : "shorts", "number" : 2 ],
[ "name" : "top", "number" : 2 ]
]

然后你可以像这样使用 Swift 的 filter 函数简单地过滤数组:

let filteredProducts = products.filter({ product in
product["number"] == 2
})

或者更短:

let filteredProducts = products.filter{$0["number"] == 2}

filteredProducts 将包含每个 product number = 2。然后,您可以将该数组用于您的 UICollectionView,或者只是覆盖您现有的 products 变量。

我不知道有关您的 Products 对象的详细信息,但您可能想要执行以下操作:

let filteredProducts = products.filter{$0.number == 2}

关于ios - 使用数组项属性值显示在 UITableView/UICollectionView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31724837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com