SWIFT 4 UISearchBar 和 UITableView

SWIFT 4 UISearchBar and UITableView

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

@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({[=11=].lowercased().prefix(searchText.count) == searchText.lowercased()})
        searching = true
        tblView.reloadData()
    }

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

替换

searchedSchool = schoolnames.filter({[=10=].lowercased().prefix(searchText.count) == searchText.lowercased()})

searchedSchool = schoolnames.filter { [=11=].range(of: searchText, options: .caseInsensitive) != nil }

我认为您必须让 searchBar 实现 containsString 方法才能实现您的需要。作为参考,请查看此 link