如何在tableview中的一个部分下面有多个项目按字母顺序排序?

时间:2016-03-01 04:44:12

标签: swift core-data nsfetchedresultscontroller

我已经实现了FetchedControllerDelegate,并且我对表视图进行了排序,以便按字母顺序显示所有内容,并且节标题正在工作。但是,对于带有字母“T”的部分,如果地点的名称不是 exact 相同的单词,则tableview有两个不同的部分。例如,对于“Taco Bell”和“Texas”,它们各自处于具有标签“T”的不同部分。我想要它,以便以“T”开头的每个单词都在“T”部分名称下。我已经找到了关于如何做到这一点的信息,但它已经用于Obj-C而不是Swift。此外,还有一些涉及设置瞬态属性的答案,但我不知道从哪里开始实现

How to use the first character as a section name

NSFetchedResultsController with sections created by first letter of a string

    // Add Sort Descriptors
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    // Initialize Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, 
        managedObjectContext: self.managedObjectContext, 
        sectionNameKeyPath: "name", cacheName: nil)

然后是表视图方法:

    override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    return fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index)
}

override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return fetchedResultsController.sectionIndexTitles
}

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 20
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if let sections = fetchedResultsController.sections {
        let currentSection = sections[section]
        if let char = currentSection.name.characters.first {
            return String(char)
        }
        return currentSection.name
    }

    return nil
}

1 个答案:

答案 0 :(得分:2)

NSManagedObject子类中添加一个计算属性,并在其中返回名称的第一个字符,

var nameFirstChar: String {
    get {
        if let char = self.name?.characters.first {
            return String(char)
        }
        return "#"
    }
}

现在将nameFirstChar设置为部分键路径,如

let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "nameFirstChar", cacheName: nil)
相关问题