如何在swift中的tableView中使用联系人制作字母部分

时间:2018-03-27 14:59:44

标签: swift uitableview

我是Swift的新手,我有使用CNContact(familyName,givenName,phoneNumber)制作的数组。

我想按名称联系字母顺序并将它们分组,以便将它们放在“titleForHeaderInSection”中,如下所示。

iOS contacts screenshot

有谁知道如何分组并将其放入titleForHeaderInSection?

struct AddressModel { 
    let nameAndPhone: [AddressContact]
}

struct AddressContact {
    let contact: CNContact
}

class AddressViewController: UITableViewController {

    var addressArray = [AddressModel]()

    private func fetchContacts() {
        print("Attempting to fetch contacts today")

        let store = CNContactStore()

        store.requestAccess(for: .contacts) { (granted, err) in
            if let err = err {
                print("Failed to request access:", err)
                return
            }
            if granted {
                let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]
                let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
                request.sortOrder = CNContactSortOrder.userDefault

                do {
                    var addressContact = [AddressContact]()
                    try store.enumerateContacts(with: request, usingBlock: { (contact, stop) in
                    addressContact.append(AddressContact(contact: contact))
                 })
                 let nameAndPhone = AddressModel(nameAndPhone: addressContact)
                 self.addressArray = [nameAndPhone] 
            } catch let err {
                print("Failed to enumerate contacts:", err)
            }
        } else {
            print("Access denied..")
        }
    }
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Section \(section)"
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return self.addressArray.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.addressArray[section].nameAndPhone.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    let nameAndPhone = addressArray[indexPath.section].nameAndPhone[indexPath.row]

    let fullName = nameAndPhone.contact.familyName + nameAndPhone.contact.givenName
    cell.textLabel?.text = fullName
    return cell
}

2 个答案:

答案 0 :(得分:1)

试试这个

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
  // ...
}

答案 1 :(得分:0)

要对部分标题进行排序,请尝试关闭:

sectionTitle = sectionTitle.sorted(by: { $0 < $1 }) // First argument smaller then second argument.