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

Using an Array Items Property Value to display in UITableView/UICollectionView

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

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

在我的应用程序中,我有一个提取请求,我创建了一个数组以显示在 collectionView 中。每个 Product 都有一个名为 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()
}

集合视图:

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{[=12=]["number"] == 2}

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

我不知道你的 Products 对象的详细信息,但你可能想做类似的事情:

let filteredProducts = products.filter{[=13=].number == 2}