【发布时间】:2018-09-08 22:23:20
【问题描述】:
我目前正在开发一个联系人应用程序,只是为了测试一些功能,但我被搜索栏卡住了。我无法在主页中的所有联系人之间进行搜索。 Swift 4.2 和 Xcode 10
class ContactsViewController: UITableViewController, CNContactViewControllerDelegate, UISearchBarDelegate {
// Outlet for Search Bar
@IBOutlet weak var searchBar: UISearchBar!
这是我在 IBOutlet 上的代表的定义
然后我的功能是在主页中显示联系人
/ * Show Contacts *
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if contactList != nil {
return contactList.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
let contact: CNContact!
contact = contactList[indexPath.row]
cell.textLabel?.text = "\(contact.givenName) \(contact.familyName)"
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let contact = contactList[indexPath.row]
let controller = CNContactViewController(for: contact)
navigationController?.pushViewController(controller, animated: true)
}
我如何使用这个 searchBar 来查看我的联系人,并使用 Name 或 Surname 作为键。
这是我的尝试之一,但contains 出现错误:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
tableView.reloadData()
} else {
inSearchMode = true
filteredData = contactList.filter({$0.contains(searchBar.text!)})
tableView.reloadData()
}
}
【问题讨论】:
-
仅供参考 - 您的表视图数据源和委托方法都基于
contactList但在搜索时您会更新filteredData。在执行搜索时,您的数据源和委托方法需要基于filteredData的结果。 -
所以我应该用filteredData更改所有contactList引用?
-
搜索时,是的。
-
@rmaddy 我不知道什么时候应该使用filteredData,什么时候应该使用contactList
-
搜索时使用filteredData,不使用时使用contactList。
标签: ios swift uisearchbar contacts