【问题标题】:SWIFT 4 UISearchBar and UITableViewSWIFT 4 UISearchBar 和 UITableView
【发布时间】:2019-04-07 10:27:09
【问题描述】:

我创建了一个包含大学列表的表格视图,并创建了一个搜索栏来标记它。搜索栏有效,但前提是我准确输入学校名称。有没有办法可以更改它以搜索名称的任何部分并获得相同的结果?这是我设置的代码。

@IBOutlet weak var schoolSearch: UISearchBar!
@IBOutlet weak var tblView: UITableView!

let schoolnames = ["Long Beach City College LAC", "California State University, Bakersfield", ...]

var searchedSchool = [String]()
var searching = false

override func viewDidLoad() {
    super.viewDidLoad()
    schoolSearch.delegate = self

    self.tblView.delegate = self
    self.tblView.reloadData()
}

extension ChooseSchool: UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching {
            return searchedSchool.count
        } else {
            return schoolnames.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell
        cell?.img.image = UIImage(named: schoolnames[indexPath.row])
        cell?.lbl.text = schoolnames[indexPath.row]

        _ = tableView.dequeueReusableCell(withIdentifier: "cell")
        if searching {
            cell?.textLabel?.text = searchedSchool[indexPath.row]
        } else {
            cell?.textLabel?.text = schoolnames[indexPath.row]
        }
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = storyboard?.instantiateViewController(withIdentifier: "TestController") as? TestController
        vc?.schoolnames = schoolnames[indexPath.row]
        navigationController?.pushViewController(vc!, animated: true)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchedSchool = schoolnames.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
        searching = true
        tblView.reloadData()
    }

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

【问题讨论】:

    标签: ios swift uitableview uisearchbar


    【解决方案1】:

    替换

    searchedSchool = schoolnames.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
    

    searchedSchool = schoolnames.filter { $0.range(of: searchText, options: .caseInsensitive) != nil }
    

    【讨论】:

    • 谢谢,这解决了问题
    【解决方案2】:

    我认为你必须让你的 searchBar 实现 containsString 方法来实现你所需要的。参考看看这个link

    【讨论】:

    • 考虑为您的答案添加一些相关的代码引用,而不仅仅是一个链接,因为它们会发生变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    相关资源
    最近更新 更多