[NSFetchResultController每月的部分

问题描述 投票:0回答:2

我正在使用NSFetchResultController在我的表中显示节。我有一个NSDate属性可以按日期排序。我正确地获取了数据,我的问题是我希望各部分像July,August一样显示一年中的月份。目前,日期显示如下图所示。enter image description here

FetchRequest

var fetchResultController: NSFetchedResultsController = { () -> NSFetchedResultsController<Gratitude> in
    let fetchRequest = NSFetchRequest<Gratitude>(entityName: "Gratitude")
    let sortByDate = NSSortDescriptor(key: "date", ascending: false)
    fetchRequest.sortDescriptors = [sortByDate]
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: Context.shared.persistentContainer.viewContext, sectionNameKeyPath: "date" , cacheName: nil)  
    return frc    
}()

标题

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    //return g2[section].monthLabel.uppercased()
   let sectionInfo = fetchResultController.sections?[section]
    return sectionInfo?.name
}

numberOfRowsInSection

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if let count = fetchResultController.sections?[section].numberOfObjects{
        return count
    }

    return 0
}

numberOfSections

func numberOfSections(in tableView: UITableView) -> Int {
    if let sections = fetchResultController.sections?.count {
        return sections
    }
   return 0

}

任何帮助将不胜感激。

更新的图像

enter image description here

swift core-data nsfetchedresultscontroller
2个回答
1
投票

[好,那么我假设sectionInfo?.name给您该日期字符串,您必须将其转换为日期并从中获取月份。您可以这样:

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  let sectionInfo = fetchResultController.sections?[section]
  return monthFrom(string: sectionInfo?.name)
}

//Make a function that converts any string with the format you showed above
//to the month for that string
func monthFrom(string: String?) -> String? {
  guard let dateString = string else { return nil }
  //Set up Date Formatter to create date object from the string
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +SSSS"
  //Verify string is a valid date
  guard let date = dateFormatter.date(from: dateString) else { return nil }
  //Pull month name from date
  dateFormatter.dateFormat = "MMMM"
  return dateFormatter.string(from: date)
}

0
投票

这里缺少的一件事是一个临时变量,该变量仅以字符串或日期部分的形式返回月份。 sectionNameKeyPath这需要设置为它,否则将其设置为日期将在日期上创建一个节,其中包括秒,分钟,小时,天等等。因此,您确实需要使用一些表示日期的年月而不是整个月的数据。我在苹果网站上看到了一个例子。

https://developer.apple.com/library/archive/samplecode/DateSectionTitles/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009939

© www.soinside.com 2019 - 2024. All rights reserved.