简体   繁体   中英

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

I know how to use an array to display in a UItableView or UICollectionView but unsure how to specify the data.

So instead of simply displaying all items in the array, to filter the results using a items property value. For for eg each item in the array has a property called number, if the number is 2 then display, products[indexPath.row].number == 2 if the .number == 1 then don't.

In my application I have a fetch request which I create an array to display in a collectionView. Each Product has a property called number , but how do I display products with a number equal to 2 ?

Fetch Request:

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()
}

CollectionView:

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

}

So, let's say you got your array of products:

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

Then you can simply filter the array using Swift's filter function like this:

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

Or even shorter:

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

filteredProducts will then contain every product with number = 2 . You can then use that array for your UICollectionView or simply just override your existing products variable.

I don't know the details about your Products object, but you probably want to do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM