【发布时间】:2015-07-30 13:13:45
【问题描述】:
我知道如何使用数组在UItableView 或UICollectionView 中显示,但不确定如何指定数据。
因此,不是简单地显示数组中的所有项目,而是使用项目属性值过滤结果。例如,数组中的每个项目都有一个名为 number 的属性,如果数字是 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()
}
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
}
【问题讨论】:
-
在您获取数据后过滤
products(删除带有 .numbers != 2 的数据)。 SO中有很多关于使用自定义对象过滤数组的问题。
标签: ios arrays swift uitableview uicollectionview