2017-07-26 52 views
1

我正在使用NSFetchedResultsController來填充tableView。 tableView可以變得很長,因爲它顯示了一個人的列表,我想按字母順序排序。我知道我需要使用titleForHeaderInSection,但我堅持如何獲得我的fetchedObjectsController.fetchedObjects中每個對象的第一個字母,並將其顯示爲部分標題以及對它進行排序,即聯繫人應用程序的工作方式。如何使用NSFetchedResultsController創建按字母順序排列的標題 - Swift 3

這是我的視圖控制器的樣子。

var fetchedResultsController: NSFetchedResultsController<Client> = { 
    let fetchRequest: NSFetchRequest<Client> = Client.fetchRequest() 
    let sortDescriptors = [NSSortDescriptor(key: "name", ascending: false)] 
    fetchRequest.sortDescriptors = sortDescriptors 
    return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.context, sectionNameKeyPath: "name", cacheName: nil) 
}() 

override func numberOfSections(in tableView: UITableView) -> Int { 
    guard let sections = fetchedResultsController.sections else { return 0 } 
    return sections.count 
} 


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    guard let sections = fetchedResultsController.sections else { return 0 } 
    return sections[section].numberOfObjects 
} 


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "clientCell", for: indexPath) 
    let client = fetchedResultsController.object(at: indexPath) 
    cell.textLabel?.text = client.name 

    return cell 
} 

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     let client = fetchedResultsController.object(at: indexPath) 
     ClientController.sharedController.delete(client) 
    } 
} 
+0

我的回答對你有幫助嗎? –

回答

0

這是你如何能得到您的標題文本,我使用一個類只能用於測試只有名字,然後使用characters.prefix我們得到的名稱和鑄造後的第一個字符應用map一個非常小的例子到String和排序,我們有你需要的

var arrayOfUsers : [User] = [User(name:"test"),User(name:"pest"),User(name:"aest"),User(name:"nest"),User(name:"best")] 
let finalArray = arrayOfUsers.map({String.init($0.name.characters.prefix(1)) }).sorted(by: {$0 < $1}) 
debugPrint(finalArray) 

控制檯日誌結果

[ 「A」, 「b」, 「N」, 「p」, 「T」]

希望這可以幫到你

相關問題