ios - 搜索栏显示正确但按错误
问题描述
我已将搜索栏添加到我的联系人应用程序中,但在搜索姓名或姓氏后返回正确的联系人。但在新闻中返回错误的联系方式。这是我的代码:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let store = CNContactStore()
store.requestAccess(for: .contacts, completionHandler: { (success, error) in
if success {
let keys = CNContactViewController.descriptorForRequiredKeys()
let request = CNContactFetchRequest(keysToFetch: [keys])
request.sortOrder = CNContactSortOrder.givenName
do {
self.contactList = []
try store.enumerateContacts(with: request, usingBlock: { (contact, status) in
self.contactList.append(contact)
})
} catch {
print("Error")
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
})
}
这是我的搜索栏功能:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
self.tableView.reloadData()
} else{
inSearchMode = true
filteredData = contactList.filter {
$0.givenName.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil ||
$0.familyName.range(of: searchBar.text!, options: [.caseInsensitive, .diacriticInsensitive ]) != nil
}
self.tableView.reloadData()
}
}
更新:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let contact = contactList[indexPath.row]
let controller = CNContactViewController(for: contact)
navigationController?.pushViewController(controller, animated: true)
}
解决方案
正如我在上面的评论中所建议的,您正在从contactList(或完整的联系人列表)中选择一个项目,但是在搜索模式下,索引显然不会匹配。
您需要检查您当前是否显示一组过滤的结果,然后根据该信息选择联系人。
也许是这样的:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var contact: CNContact
if inSearchMode {
contact = filteredData[indexPath.row]
} else {
contact = contactList[indexPath.row]
}
let controller = CNContactViewController(for: contact)
navigationController?.pushViewController(controller, animated: true)
}
推荐阅读
- python - 如何使用 uuid 创建自定义字段?
- python - 训练后如何获得模型的最高准确率
- flutter - 仅从 Flutter 中的完整日期中提取年份
- android - 如何修复:DexCountException:无法运行 dx
- angular - Angular 11:Msal Angular V2 包的问题
- python-3.x - 有没有办法将 python 与入侵检测系统集成?(描述中的详细问题)
- android-studio - 使用滑动手势在 Android Studio 中导航不同的屏幕?
- javascript - 如果选中,如何获取复选框下拉值?
- python - 将 x 天添加到今天的日期,其中 x 太大而无法转换
- angular - 使用@ngrx/data,您如何在自定义数据服务上形成从更新到实体的 JSON 补丁文档?