我正在尝试使用UISearchController创建搜索功能.但是,我似乎无法使其与我的团队对象一起工作.我首先创建了一个包含id,name和shortname的Team Object.然后我从一个url中检索teamData,并将Team Objects添加到一个填充到tableView中的数组中.这个tableView包含一个searchController,它假设过滤数据,但没有任何反应.
阵列
var teamArray = Array<Team>() var filteredTableData = [String]()
GetTeams功能
func getTeams(url: String) { isApiCalling = true request(.GET,url,parameters: nil) .response { (request,response,data,error) in if error == nil { let data: AnyObject = data! let jsonArray = JSON(data: data as! NSData) for (key: String,subJson: JSON) in jsonArray { // Create an object and parse your JSON one by one to append it to your array var newTeamObject = Team(id: subJson["id"].intValue,name: subJson["name"].stringValue,shortname: subJson["shortname"].stringValue) self.teamArray.append(newTeamObject) } self.isApiCalling = false self.tableView.reloadData() self.refreshControl?.endRefreshing() } } }
的cellForRowAtIndexPath
override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("teamCell",forIndexPath: indexPath) as! TeamCell cell.textLabel?.font = UIFont(name: "HelveticaNeue-Light",size: 20) cell.textLabel?.text = self.teamArray[indexPath.row].name as String if (self.cellSelected.containsObject(indexPath)) { cell.accessoryView = cell.accessoryCheck } else { cell.accessoryView = cell.accessoryUncheck } return cell }
筛选数据
func updateSearchResultsForSearchController(searchController: UISearchController) { filteredTableData.removeAll(keepCapacity: false) let searchPredicate = nspredicate(format: "SELF CONTAINS[c] %@",searchController.searchBar.text) let array = (teamArray as NSArray).filteredArrayUsingPredicate(searchPredicate) filteredTableData = array as! [String] self.tableView.reloadData() }
团队对象
class Team{ var id: Int! var name: Nsstring! var shortname: Nsstring! init(id: Int,name:Nsstring,shortname: Nsstring) { self.id = id self.name = name self.shortname = shortname } }
解决方法
teamArray中的对象没有SELF属性.您不能使用SELF一次搜索对象的所有属性.您必须提供属性的名称,如果要搜索多个属性,则必须将所有这些属性添加到谓词中.
我认为你可以在name属性中搜索如下:
let searchPredicate = nspredicate(format: "name CONTAINS[c] %@",searchController.searchBar.text)
如果您需要更多属性,请执行以下操作:
let searchPredicate = nspredicate(format: "name CONTAINS[c] %@ OR shortname CONTAINS[c] %@",searchController.searchBar.text,searchController.searchBar.text)