tra*_*scu 2 contacts uisearchbar ios swift
我目前正在使用“联系人”应用程序,只是为了测试某些功能,而我一直受搜索栏困扰。我无法在首页中的所有联系人之间进行搜索。Swift 4.2和Xcode 10
class ContactsViewController: UITableViewController, CNContactViewControllerDelegate, UISearchBarDelegate {
// Outlet for Search Bar
@IBOutlet weak var searchBar: UISearchBar!
Run Code Online (Sandbox Code Playgroud)
这是我在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)
}
Run Code Online (Sandbox Code Playgroud)
如何使用searchKey用作关键字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()
}
}
Run Code Online (Sandbox Code Playgroud)
您的contactList数组包含CNContact实例。因此$0,您的filter是CNContact。contains失败,因为CNContact没有contains方法。
考虑一下,如果您只有一个CNContact变量,并且想查看联系人的姓名是否包含搜索文本,则需要写些什么。
您可能不想要,contains因为您可能想要进行不区分大小写,变音符号的搜索。
这是查看联系人的给定和姓氏属性的示例。根据需要添加其他属性:
filteredData = contactList.filter {
$0.givenName.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil ||
$0.familyName.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1433 次 |
| 最近记录: |