在您的类中添加这些 UISearchBarDelegate 方法,您的类必须使用代码self.yourSearchBar.delegate = self
或情节提要确认此协议。
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.text = ""
searchBar.resignFirstResponder()
self.searchedArrayToDisplay = self.listDataArray
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "\n" {
searchBar.resignFirstResponder()
} else if searchText == "" {
self.searchedArrayToDisplay = self.listDataArray
} else {
self.filterContentForSearchText(searchText)
}
}
func filterContentForSearchText(searchText: String) {
self.searchedArrayToDisplay = self.listDataArray.filter({(eachObject: [String:AnyObject]) -> Bool in
let name = eachObject["name"] as! String
let stringMatch = name.lowercaseString.rangeOfString(searchText.lowercaseString)
let result = stringMatch != nil ? true : false
return result
})
}
现在在单元格中用于索引路径方法
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell : UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Value1, reuseIdentifier:"cell")
var object = self.searchedArrayToDisplay[indexPath.row]
}