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

标签 ios swift uitableview core-data nsfetchedresultscontroller

我正在制作一个 iOS sleep 跟踪器应用程序,它有两个 CoreData 属性:

sleepStartTime 和 sleepEndTime 的类型为 Date()

“我的 sleep 历史记录”选项卡当前如下所示:

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)
}

最佳答案

如果你想要组数据也许你可以尝试这个

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

关于ios - 如何在 Swift(iOS) 中按月对 UITableView 数据进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53148745/

相关文章:

php - 在 Swift 中检索和使用整个 MYSQL 表

swift - 在 Swift 中初始化类属性

ios - UIImageView 上的宽度和高度 NSLayoutConstraints 不起作用

ios - 使用搜索显示 Controller 时隐藏普通 UITableView

ios - 数组和表格 View : only add new items

ios - postNotificationName 是否保证立即发送给监听者?

ios - 检查数组值是否等于字符串

iphone - 当文本已添加到 UITextFields 时,如何在 UIReturnKeyGo 和 UIReturnKeyNext 之间切换?

ios - 在 iOS 中验证单个文本字段中的两个值

ios - 消息已发送到已释放的对象 (ARC)