gpt4 book ai didi

swift - NSFetchedResultsController 部分按月

转载 作者:行者123 更新时间:2023-11-28 14:26:44 25 4
gpt4 key购买 nike

我正在使用 NSFetchResultController 来显示表格中的部分。我有一个 NSDate 属性来按日期排序。我正在正确获取数据,我的问题是我希望这些部分显示一年中的月份,例如 七月、八月。目前日期显示如下图所示。 enter image description here

获取请求

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

最佳答案

好吧,那么我假设 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)
}

关于swift - NSFetchedResultsController 部分按月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51509746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com