如何在Swift(iOS)中按月对UITableView数据进行分组?

时间:2018-11-05 05:21:38

标签: ios swift uitableview core-data nsfetchedresultscontroller

我正在制作一个iOS睡眠跟踪器应用程序,该应用程序具有两个CoreData属性:

sleepStartTime and sleepEndTime类型为Date()

“我的睡眠历史”标签当前如下所示:

sleep history tab screenshot

如何按月和年组织数据,并在Swift中相应地为该部分(例如,2018年11月)命名。

更新:

这是我当前的代码-

var sleepHistory: [NSManagedObject]?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(false)

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "SleepEntryDetail")
    let sort = NSSortDescriptor(key: "sleepStart", ascending: false)
    fetchRequest.sortDescriptors = [sort]

    do {
        sleepHistory = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch data. \(error), \(error.userInfo)")
    }

    tableView.reloadData()
}



// MARK: - Table view data source


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sleepHistory?.count ?? 0
}

override func tableView(_ tableView: UITableView, cellForRowAt  indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SleepHistoryCell", for: indexPath)


let sleepDetail = sleepHistory![indexPath.row]

let sleepDuration = (sleepDetail.value(forKeyPath: "sleepEnd") as! Date).timeIntervalSince(sleepDetail.value(forKeyPath: "sleepStart") as! Date)

cell.textLabel?.text = "\(dateFormatter(date: (sleepDetail.value(forKeyPath: "sleepStart") as! Date)))"
cell.detailTextLabel?.text = "Duration: \(timeString(time: sleepDuration))"

return cell
}

func dateFormatter(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy '-' h:mm a"
 //http://nsdateformatter.com useful dataformatter resource
return dateFormatter.string(from:date)
}

func timeString(time: TimeInterval) -> String {
let hours = Int(time)/3600
let minutes = Int(time)/60 % 60
let seconds = Int(time) % 60
return String(format: "%02i:%02i:%02i", hours, minutes, seconds)
}

1 个答案:

答案 0 :(得分:0)

如果您想要组数据,可以尝试一下

let groupByDate = Dictionary(grouping: data, by: { (element) -> String in
            return data.date
        }