有没有一种方法可以使用多个键选择器对UILocalizedIndexedCollat​​ion进行排序?

时间:2019-02-07 03:44:57

标签: ios swift

我正在尝试对CNContacts进行排序,以使用UILocalizedIndexedCollat​​ion为TableView创建节索引。我找不到使用诸如familyName和GivenName之类的多个键进行排序的方法。我已经尝试过使用数组和元组,但是我没有尝试过,似乎选择器只能接受单个字符串。无论如何,要传递选择器多个键?

class SectionIndexesTableViewController: UITableViewController {

    let collation = UILocalizedIndexedCollation.current()
    var sections: [[CNContact]] = []
    var sectionTitles: [String] = []
    var contacts: [CNContact] = [] {
        didSet {
            sectionTitles.removeAll()
            sections.removeAll()
            let selector: Selector = #selector(getter: CNContact.familyName)
//            let selector: Selector = #selector(getter: (CNContact.familyName, CNContact.givenName))  // Error: Instance member 'familyName' cannot be used on type 'CNContact'
            var sectionsAll = Array(repeating: [], count: collation.sectionTitles.count)
            let sortedContacts = collation.sortedArray(from: contacts, collationStringSelector: selector)
            for contact in sortedContacts {
                let sectionNumber = collation.section(for: contact, collationStringSelector: selector)
                sectionsAll[sectionNumber].append(contact as! CNContact)
            }
            for index in 0 ..< sectionsAll.count {
                if sectionsAll[index].count > 0 {
                    sectionTitles.append(collation.sectionTitles[index])
                    sections.append(sectionsAll[index] as! [CNContact])
                }
            }
            self.tableView.reloadData()
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        let fetchRequest = CNContactFetchRequest(keysToFetch:
            [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
        fetchRequest.sortOrder = CNContactSortOrder.userDefault
        let store = CNContactStore()
        do {
            try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
                self.contacts.append(contact)
            })
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }
    }

    // MARK: - Table view data source

2 个答案:

答案 0 :(得分:0)

一个可能的解决方案是创建CNContact的扩展,该扩展具有只读属性,该扩展返回通过将族和给定名称按您希望排序的顺序进行连接而构建的单个字符串。

设置扩展名后,将该属性作为选择器传递给UILocalizedIndexedCollat​​ion。

答案 1 :(得分:0)

这很容易解决:

extension CNContact {

    @objc var sortKey: String {
        get {
            return familyName + givenName
        }
    }
}

并如下更改select语句:


let selector: Selector = #selector(getter: CNContact.sortKey)