ios - Swift UITableview 单元格搜索不起作用

标签 ios swift

我的场景,我正在尝试为我的 UITableview 实现搜索选项。在这里,我在 UITableview 中使用自定义单元格。在我的数组数据中,我还添加了部分。如何解决这个问题?

下面是我的代码

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchBarDelegate {

          var allDetails:[(String,[String])] = []
          var searchResult:[(String,[String])] = []
          @IBOutlet weak var tableVIew: UITableView!
          @IBOutlet weak var searchBar: UISearchBar!

        override func viewDidLoad() {
            super.viewDidLoad()
            allDetails = [("Vadavalli",["Vadvalli", "Mullai Nagar", "P.N.Pudhur"]),
                              ("R.S.Puram",["Lawly Road", "Kowly Brown", "D.B Road"]),
                              ("Town Hall",["Raja Street", "Gandhipark", "Five corner road", "Main Town Hall"])]
            searchResult = allDetails    
          }

        func numberOfSections(in tableView: UITableView) -> Int {
            return searchResult.count
          }

          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return searchResult[section].1.count
          }

          func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return searchResult[section].0
          }

          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
            if cell == nil{
              cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
            }
            cell?.textLabel?.text = searchResult[indexPath.section].1[indexPath.row]
            return cell!
          }

          func updateSearchResults(for searchController: UISearchController) { // SEARCH NOT WORKING
             if let searchText = searchController.searchBar.text {
                    searchResult = allDetails.map({ (areaTitle:$0.0,areas:$0.1.filter({ $0.lowercased().contains(searchText) })) }).filter { !$0.1.isEmpty}
                    //self.tableVIew.reloadData();
                }
            }
}

最佳答案

您需要做的是实现UISearchBarDelegate方法searchBar(_:textDidChange:)。每次搜索栏文本更改时都会调用此函数。在此方法中,我们可以过滤 allDetails 并重新加载表格 View 。

我们基本上会将 updateSearchResults(for searchController:) 方法中的所有代码移至 searchBar(_:textDidChange:) 委托(delegate)方法。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchBarDelegate {
    var allDetails:[(String,[String])] = []
    var searchResult:[(String,[String])] = []
    @IBOutlet weak var tableVIew: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    override func viewDidLoad() {
        super.viewDidLoad()
        //New line of code! Be sure to set your search bar's delegate in viewDidLoad()
        searchBar.delegate = self
        allDetails = [("Vadavalli",["Vadvalli", "Mullai Nagar", "P.N.Pudhur"]),
                  ("R.S.Puram",["Lawly Road", "Kowly Brown", "D.B Road"]),
                  ("Town Hall",["Raja Street", "Gandhipark", "Five corner road", "Main Town Hall"])]
        searchResult = allDetails
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return searchResult.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchResult[section].1.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return searchResult[section].0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        }
        cell?.textLabel?.text = searchResult[indexPath.section].1[indexPath.row]
        return cell!
    }

    //Let's get rid of this function
    /*
    func updateSearchResults(for searchController: UISearchController) {
        // SEARCH NOT WORKING
        if let searchText = searchController.searchBar.text {
            searchResult = allDetails.map({ (areaTitle:$0.0,areas:$0.1.filter({ $0.lowercased().contains(searchText) })) }).filter { !$0.1.isEmpty }
            //self.tableVIew.reloadData();
        }
    }*/

    //And implement the UISearchBarDelegate method. This method fires every time that the search bar's text changes
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchResult = allDetails.map({ (areaTitle:$0.0,areas:$0.1.filter({ $0.lowercased().contains(searchText) })) }).filter { !$0.1.isEmpty }
        self.tableView.reloadData();
    }
}

关于ios - Swift UITableview 单元格搜索不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57344545/

相关文章:

ios - UIWebView 专注于特定方 block

ios - swift 3 中 View Controller 的重复实例

swift - UITextField 上的 "uppercaseString"和 "lowercaseString"在 Swift 中崩溃

ios - 是否可以创建多行 UISegmentedControl?

ios - 错误: 'Call can throw but is not marked with try and error not handled'

ios - iOS 11 beta 5 中的位置蓝色条在哪里?

ios - 如何使用 Moya 取消多个网络请求

ios - 从 [String :AnyObject] to unrelated type NSMutableDictionary always fails Warning

ios - Alamofire:[结果]:失败:错误域=NSURLErrorDomain 代码=-999 "cancelled"

ios - UiTextField leftViewMode 奇怪的行为.. Bug?