如何在搜索栏swift的表视图结果中加载数据

时间:2017-06-26 21:00:42

标签: swift uitableview uisearchbar uisearchbardelegate

我想在tableView中显示SearchBar的搜索结果,我不知道如何。

enter image description here

当我在TextField中输入一个目的地时,一切都运行得很好,但是当我输入SearchBar时不能正常工作:

enter image description here

以下是如何在[String]中调用func进行搜索:

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
}}

扩展名ViewController: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)
    }

}}

可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

首先,您的班级originalfiltered

应该有两个数组
var originalData: [String]!
var filteredData: [String]!

在班级中添加searchController

let searchController = UISearchController(searchResultsController: nil)

设置您的searchController并添加searchBar作为tableView标题

searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.delegate = self
searchController.searchBar.placeholder = "Search"
searchController.searchBar.sizeToFit()
searchController.hidesNavigationBarDuringPresentation = false

tblView.tableHeaderView = searchController.searchBar

实施searchBar' delegate方法

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchController.searchBar.text = ""
    tblView.reloadData()
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    let searchString = searchController.searchBar.text
    filteredData = originalData.filter({ (item) -> Bool in
        let value: NSString = item as NSString
        return (value.range(of: searchString!, options: .caseInsensitive).location != NSNotFound)
    })
    tblView.reloadData()
}

最后,您的tableView delegate方法看起来像这样

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searchController.isActive == true && searchController.searchBar.text != "" {
        return filteredData.count
    }
    return originalData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if searchController.isActive == true && searchController.searchBar.text != "" {
        //RETURN CELLS CREATED FROM FILTERED DATA
    }
    //RETURN CELLS CREATED FROM ORIGINAL DATA
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if searchController.isActive == true && searchController.searchBar.text != "" {
        //HANDLE ROW SELECTION FROM FILTERED DATA
    }
    //HANDLE ROW SELECTION FROM ORIGINAL DATA
}

答案 1 :(得分:0)

好的......所以我解决了我的问题。 @Malik让我心胸开阔! (感谢那!) 最后,我以编程方式执行searchBar:

    let searchController = UISearchController(searchResultsController: nil)
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.delegate = self
    searchController.searchBar.placeholder = "Buscar Destinos"
    searchController.searchBar.sizeToFit()
    searchController.hidesNavigationBarDuringPresentation = false

并在我的TableView中显示:

tableView.tableHeaderView = searchController.searchBar

我使用UISearchBarDelegate:

                                                                              `extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    let stringOfUser = (searchController.searchBar.text!)

    DestinoP.searchDestinos(stringOfUser)

}}

在tableView中显示结果:

 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

        if let str = autoCompleteDestino[index].desDestino {
            cell.textLabel?.text = str
        }

    return cell
}}

tableView的reloadData:

func mostarResultados( ArrayResultados: [Destinos]) {

    autoCompleteDestino = ArrayResultados
    tableView.reloadData()
}

谢谢!