【问题标题】:Using an Array Items Property Value to display in UITableView/UICollectionView使用数组项属性值在 UITableView/UICollectionView 中显示
【发布时间】:2015-07-30 13:13:45
【问题描述】:

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

因此,不是简单地显示数组中的所有项目,而是使用项目属性值过滤结果。例如,数组中的每个项目都有一个名为 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


【解决方案1】:

所以,假设您有一系列产品:

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 将包含每个productnumber = 2。然后,您可以将该数组用于您的 UICollectionView,或者直接覆盖您现有的 products 变量。

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

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

【讨论】:

  • 谢谢,我是iOS开发新手,忽略了过滤方法。使用闭包的过滤方法非常干净。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多