Ios 有没有一种方法可以使用多键选择器使用UILocalizedIndexedCollation进行排序?
我正在尝试对CNContacts进行排序,以便使用UILocalizedIndexedCollation为TableView创建节索引。我找不到使用多个键(如familyName和givenName)进行排序的方法。我尝试过使用数组和元组,但无论我尝试什么,选择器似乎只能接受单个字符串。是否仍要传递选择器多个键Ios 有没有一种方法可以使用多键选择器使用UILocalizedIndexedCollation进行排序?,ios,swift,Ios,Swift,我正在尝试对CNContacts进行排序,以便使用UILocalizedIndexedCollation为TableView创建节索引。我找不到使用多个键(如familyName和givenName)进行排序的方法。我尝试过使用数组和元组,但无论我尝试什么,选择器似乎只能接受单个字符串。是否仍要传递选择器多个键 class SectionIndexesTableViewController: UITableViewController { let collation = UILocal
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
一种可能的解决方案是创建CNContact的扩展,该扩展具有只读属性,该属性返回一个字符串,该字符串是通过按照您希望的排序顺序连接族和给定名称而生成的
设置扩展后,将该属性作为选择器传递给UILocalizedIndexedCollation 一种可能的解决方案是创建CNContact的扩展名,该扩展名具有只读属性,该属性返回一个字符串,该字符串是通过按照您希望的排序顺序连接族和给定名称而生成的
设置扩展后,将该属性作为选择器传递给UILocalizedIndexedCollation 这就是解决方案的简单程度:
extension CNContact {
@objc var sortKey: String {
get {
return familyName + givenName
}
}
}
并按如下方式更改select语句:
let selector: Selector = #selector(getter: CNContact.sortKey)
这就是解决方案的简单程度:
extension CNContact {
@objc var sortKey: String {
get {
return familyName + givenName
}
}
}
并按如下方式更改select语句:
let selector: Selector = #selector(getter: CNContact.sortKey)
哇!这是一个很好且易于实现的解决方案。谢谢你的提示。这是一个我一直在努力的例子,从跟随教程到设计自己的代码。我不知道何时何地使用什么。哇!这是一个很好且易于实现的解决方案。谢谢你的提示。这是一个我一直在努力的例子,从跟随教程到设计自己的代码。我不知道何时何地使用什么。最好在族和名字之间加逗号或其他标点符号,以避免出现一些可能的边缘情况。最好在族和名字之间加逗号或其他标点符号,以避免出现一些可能的边缘情况。