【发布时间】:2017-06-26 21:00:42
【问题描述】:
我想在tableView中显示SearchBar的搜索结果,不知道怎么做。
当我在 TextField 中输入 Destination 时,一切正常,但当我在 SearchBar 中输入时却无法正常工作:
这里是如何调用一个 func 在 [String] 中搜索:
extension ViewController: UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let substring = (textField.text! as NSString).replacingCharacters(in: range, with: string)
DestinoP.searchDestinos(substring)
return true
}}
这里是如何显示结果:
extension ViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
let index = indexPath.row as Int
isSearching = true // this is just for SearchBar
if isSearching {
if let str = autoCompleteDestino[index].desDestino {
cell.textLabel?.text = str
}
}
return cell
}}
扩展视图控制器:UITableViewDelegate {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isSearching { // this is just for SearchBar
return autoCompleteDestino.count
}
return autoCompleteDestino.count
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)!
destinoSearch.text = selectedCell.textLabel!.text!
busquedaDestinosText.text = selectedCell.textLabel!.text!
}}
这是我在 SearchBar 中键入时尝试显示结果的方式:
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let stringOfUser = (busquedaDestinosText.text)
DestinoP.searchDestinos(stringOfUser!)
if destinoSearch.text == "" {
isSearching = false
view.endEditing(true)
tableView.reloadData()
print(isSearching)
} else {
isSearching = true
print(isSearching)
print(autoCompleteDestino)
}
}}
可以帮助我吗?
【问题讨论】:
标签: swift uitableview uisearchbar uisearchbardelegate