在“ UISearchbar”中搜索名称或号码

时间:2019-03-30 09:49:43

标签: ios swift uitableview uisearchbar uisearchbardelegate

tableViewCell中,我有userNameLbl,名字,userClgLbl,有数字。我想在tableView中搜索并显示数据,无论是名称搜索还是数字搜索。

如果用户搜索名称-基于名称,我可以在tableView中显示数据。
如果用户搜索号码-基于号码,我可以在tableView中显示数据。

但是如何使用单个搜索栏的名称和编号。实际上,我的数据是来自服务器的动态数据,而号码不是电话号码。

UISearchBarDelegate已添加到我的课程

let searchBar = UISearchBar()
var filteredData: [Any]!
@IBOutlet weak var listTblView: UITableView!

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return filteredData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // create a new cell if needed or reuse an old one
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell


    cell.userNameLbl.text = filteredData[indexPath.row] as? String
    cell.userClgLbl.text = clg_uniq[indexPath.row] as? String

    return cell

} 

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    let strArr:[String] = clg_uniq as! [String]
    filteredData = searchText.isEmpty ? clg_uniq : strArr.filter({(dataString: String) -> Bool in
        // If dataItem matches the searchText, return true to include it
        return dataString.range(of: searchText, options: .caseInsensitive) != nil
    })

    DispatchQueue.main.async {
        self.listTblView.reloadData()
    }
    if searchText == "" {
        DispatchQueue.main.async {
            searchBar.resignFirstResponder()
        }
    }
}

//Added these lines after json parsing 
self.filteredData = self.clg_uniq
self.listTblView.reloadData()

我的示例JSON数据是

{"log" =     (
            {
        Name = "Name1";
        "clg_uniq" = 5c640e7b86e35;
    },
            {
         Name = "Name2";
        "clg_uniq" = <null>;
    },
            {
         Name = <null>;
        "clg_uniq" = 5c647af5d5c4d;
    },
            {
         Name = "Name4";
        "clg_uniq" = 5c647a0427253;
    },
            {
         Name = <null>;
        "clg_uniq" = <null>;
    },
            {
         Name = "Name6";
        "clg_uniq" = $cuniq";
    },
 )
}

1 个答案:

答案 0 :(得分:1)

添加以下变量-

var logArray = [Dictionary<String, Any>]() // For all result
var searchedLogArray = [Dictionary<String, Any>]() // For filtered result
var searchActive = false // whenever user search anything

替换 UISearchBarDelegate-

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    searchActive = searchText.count > 0 ? true : false

    let namePredicate = NSPredicate(format: "Name CONTAINS[c] %@", searchText)
    let clgUniqPredicate = NSPredicate(format: "clg_uniq CONTAINS[c] %@", searchText)

    let compoundPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [namePredicate, clgUniqPredicate])

    searchedLogArray = logArray.filter({
        return compoundPredicate.evaluate(with: $0)
    })

    listTblView.reloadData()

}

替换 UITableViewDataSource-

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return searchActive ? searchedLogArray.count : logArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // create a new cell if needed or reuse an old one
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell

    let logDict = searchActive ? searchedLogArray[indexPath.row] : logArray[indexPath.row]

    // Name
    if let name = log["Name"] as? String{

      cell.userNameLbl.text = name

    }else{

      cell.userNameLbl.text = ""

    }


    // clg_uniq
    if let clgUniq = log["clg_uniq"] as? String {

         cell.userClgLbl.text = clgUniq

    }else{

         cell.userClgLbl.text = ""

    }


    return cell

}

我希望您以Dictionary<String, Any>

让我知道您是否仍然有任何问题。