I just implemented a filtering mechanism in my UICollectionView
and I think this is not the correct methodology I should have chosen.
How can I improve my code to make it have better performance?
I have a screen where you input your criterias for filtering, and then this code handles the rest:
extension ProductsCollectionViewController
{
@objc func Filter()
{
performSegue(withIdentifier: "segue_to_filter_view", sender: self)
}
@IBAction func unwindFromFilterScreenAccept(segue: UIStoryboardSegue)
{
if segue.source is FilterViewController
{
if let senderVC = segue.source as? FilterViewController
{
if senderVC.chosenCategory != "" {categoryFilter = senderVC.chosenCategory}
self.areFiltersSet = true
}
}
self.tabBarController?.tabBar.isHidden = false
self.products.removeAll()
self.LoadProducts(productsToShow: pageType)
//self.LoadProducts(productsToShow: pageType)
}
@IBAction func unwindFromClearAllFilters(segue: UIStoryboardSegue)
{
ClearAllFilters()
self.products.removeAll()
self.LoadProducts(productsToShow: pageType)
}
private func ClearAllFilters()
{
areFiltersSet = false
}
private func FilterProduct(prod: Product) -> Bool
{
if areFiltersSet == false {return true}
return FilterProductByCategory(prod:prod) && FilterProductByLocation(prod:prod) && FilterProductByCondition(prod:prod)
}
Also:
I have a search bar implemented. Will the two work together? Is there a way to properly integrate the two?
P.S:
The Filtering itself is checked when adding a product to the collection when loading products.
答案 0 :(得分:1)
通过执行搜索过滤不是最好的方法。最好根据您选择的过滤器更新collectionView本身。例如,如果您有对应于特定类别的产品,则可以执行以下操作:
let products = [Product(category: "one"), Product(category: "one"), Product(category: "two")]
let foo = products.filter {$0.category == "one"}
该过滤器功能将仅返回与类别一对应的产品。然后,您可以使用过滤后的数组填充collectionView。
关于searchBar,是的,它们将与任何其他过滤器功能一起使用。基本上,您将只执行两个过滤器:
仅供参考,如果将searchBar添加为collectionViewCell或标头,则必须重新加载带有indexPaths的项,因为reloadData()
将使searchBar退出响应者。
还有一点,作为建议,通常的做法是使用小写字母-> filter()而不是Filter()来命名您的方法。