Swift 4.2使用Contacts Framework使用搜索栏搜索联系人

时间:2018-09-08 22:23:21

标签: ios swift uisearchbar contacts

我目前正在使用“联系人”应用程序,只是为了测试某些功能,而我被搜索栏困住了。我无法在首页中的所有联系人之间进行搜索。 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如何使用键名或姓氏来查找我的联系人。

这是我的尝试之一,但是我遇到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()
    }
}

1 个答案:

答案 0 :(得分:3)

您的contactList数组包含CNContact个实例。因此,您的$0中的filterCNContactcontains失败,因为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
}
相关问题