【问题标题】:how to load data in table view result of search bar swift如何在搜索栏swift的表格视图结果中加载数据
【发布时间】: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


    【解决方案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
    

    实现searchBardelegate 方法

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

    最后,您的tableViewdelegate 方法将如下所示

    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
    }
    

    【讨论】:

    • 嗨马利克..谢谢!但在这种情况下,我在情节提要@IBOutlet weak var destinoSearch: UISearchBar 中添加了搜索栏! (不是以编程方式)。在我的情况下显示“filteredData 或 autoCompleteDestino”的方法是这样的: if let str = autoCompleteDestino[index].desDestino { cell.textLabel?.text = str } 在 SearchBar 中键入时如何显示 autoCompleteDestino?跨度>
    • 您仍然需要使用 searchBar delegate 方法。这些方法依次会过滤掉数据并重新加载tableView
    【解决方案2】:

    好的...所以我解决了我的问题。 @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()
    }
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多