Ios 搜索栏显示正确但按错误的联系人
我已将搜索栏添加到我的联系人应用程序中,但在搜索姓名或姓氏后,返回的是正确的联系人。但《新闻周刊》却回复了错误的联系人。这是我的密码:Ios 搜索栏显示正确但按错误的联系人,ios,swift,uisearchbar,Ios,Swift,Uisearchbar,我已将搜索栏添加到我的联系人应用程序中,但在搜索姓名或姓氏后,返回的是正确的联系人。但《新闻周刊》却回复了错误的联系人。这是我的密码: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let store = CNContactStore() store.requestAccess(for: .contacts, completionHandler: { (su
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)
}
正如我在上面的评论中所建议的,您正在从联系人列表(或联系人的完整列表)中选择一个项目,但在搜索模式下,索引显然不匹配 您需要检查您的联系人当前是否显示筛选的结果集,然后根据该信息选择联系人 可能是这样的:
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)
}
显示
didSelectRow
方法的代码。您应该检查inSearchMode
是否已启用,并从filteredData
中选择联系人(如果该联系人在搜索中)mode@Scriptable更新使用与cellforrowatinexpath
方法相同的逻辑获取联系人