使用方法如下:
filteredData
键入到
Human
var filteredData = [Human]()
在中更改
cellForRow
,
didSelectRowAt
和
textDidChange
.
为更改的行添加了注释。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? DataCell {
let text: String!
if inSearchMode {
text = filteredData[indexPath.row].name // changed this line only
} else {
text = members[indexPath.row].name
}
cell.textLabel?.text = text
return cell
} else {
return UITableViewCell()
}
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
tableView.reloadData()
} else {
inSearchMode = true
filteredData = members.filter { $0.name.lowercased().contains(searchBar.text!.lowercased()) } // changed this line
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if inSearchMode {
showAlert(title: "Surname is...", msg: filteredData[indexPath.row].surname) // added this line
} else {
showAlert(title: "Surname is...", msg: members[indexPath.row].surname)
}
}