swift - 如何快速搜索手机联系人
问题描述
在项目中,我正在获取我所有的联系人.. 在这里我需要按他们的名字搜索联系人如何做到这一点
我几乎完成了但无法过滤textDidChange
以下是我尝试过的代码:
class ContactsViewController1: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var joinersTableView: UITableView!
var contacts = [CNContact]()
var search = false
var searchArray = [CNContact]()
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return jsonArrayTagged.count
} else {
if search {
return searchArray.count
} else {
return contacts.count
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 1 {
var cell1: ContactsTableViewCell2 = tableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell2", for: indexPath) as! ContactsTableViewCell2
if search {
cell1.nameLbl.text = searchArray[indexPath.row].givenName + " " + searchArray[indexPath.row].familyName
cell1.empRoleLbl.text = searchArray[indexPath.row].phoneNumbers.first?.value.stringValue
cell1.inviteButn.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
} else {
cell1.nameLbl.text = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName
cell1.empRoleLbl.text = contacts[indexPath.row].phoneNumbers.first?.value.stringValue
cell1.inviteButn.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
}
return cell1
}
return UITableViewCell()
}
}
extension ContactsViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray = contacts.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
search = true
joinersTableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
search = false
searchBar.text = ""
joinersTableView.reloadData()
}
}
错误:
“CNContact”类型的值没有“小写”成员
解决方案
您不能仅将 aCNContact
用作 aString
并将其与 a 进行比较String
。您需要指定要过滤String
的属性。CNContact
如果你想搜索familyName
例如,做$0.familyName.lowerCased()
而不是$0.lowerCased
,因为$0
是一个CNContact
。
extension ContactsViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray = contacts.filter {$0.familyName.lowercased().prefix(searchText.count) == searchText.lowercased()}
search = true
joinersTableView.reloadData()
}
...
}
与您的问题无关,但您为什么只搜索文本的开头?使用localizedCaseInsensitiveContains
而不是prefix
会产生更好的用户体验。
推荐阅读
- r - R SPARQL Wikidata:“开始和结束标签不匹配”
- javascript - import 如何在导入 Angular 的模块中工作
- templates - 为带有预定义附加任务的产品积压项目创建模板
- python - 如何从动态列数中找到最大值
- javascript - A .then 在 AWS Lambda 上解决承诺后不会运行
- scala - 使用 circe-optics 解码嵌套数组
- laravel - 在“if”条件下获取数据 laravel
- ios - 你如何在 React Native 中检查/更改 iOS 版本?
- terraform - terraform - 在 yaml 中挂载目录
- python - 通过忽略零计算稀疏矩阵的平均值