如何使用搜索栏过滤JSON数据

时间:2018-07-17 06:05:33

标签: json swift filter uisearchbar

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{

    searchBar.barTintColor = UIColor.white
    let lists:Array = searchCollectionList1 as Array
   // let searchPredicate = NSPredicate(format: "assetname CONTAINS[C] %@", searchText)
    let searchPredicate = searchFilter(searchName: searchText) 'Constant 'searchPredicate' inferred to have type '()', which may be unexpected'
    let array = (lists as NSArray).adding(searchPredicate)
    filteredDataItems = array

    DispatchQueue.main.async {
         self.collectionView.reloadData()
    }


}

1 个答案:

答案 0 :(得分:0)

请勿使用NSPredicate,请使用本机filter

range(of ... ) != nil和选项.caseInsensitiveCONTAINS[C]完全相同

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{

    searchBar.barTintColor = UIColor.white
    filteredDataItems = searchCollectionList1.filter{ $0.assetname.range(of: searchText, options: .caseInsensitive) != nil }
    DispatchQueue.main.async {
        self.collectionView.reloadData()
    }
}

这假设searchCollectionList1filteredDataItems是同一类型。