首页 > 解决方案 > 如何快速搜索手机联系人

问题描述

在项目中,我正在获取我所有的联系人.. 在这里我需要按他们的名字搜索联系人如何做到这一点

我几乎完成了但无法过滤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”类型的值没有“小写”成员

标签: swiftsearchtableviewcontacts

解决方案


您不能仅将 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会产生更好的用户体验。


推荐阅读