我正在尝试返回按日期排序的以下单元格。我搜索了很多帖子,但我真的不明白我在哪里特别指定排序依据:
let sortedArray = jogs.sorted { $0.jogDate < $1.jogDate }
这是我在TableViewController中使用的功能:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCellIdentifier") as? ToDoCell else {
fatalError("Could not dequeue a cell")
}
cell.delegate = self
let jog = jogs[indexPath.row]
cell.titleLabel?.text = jog.title
cell.descriptionLabel.text = jog.notes
cell.dateLabel.text = Jog.jogDateFormatter.string(from: jog.jogDate)
return cell
}
还是应该将排序放入Struct文件中?同样,Class文件比Struct文件更好吗?
1。按日期对慢跑进行排序
override func viewDidLoad() {
super.viewDidLoad()\
jogs.sort { $0.jogDate < $1.jogDate }
tableView.reloadData()
}
或
2。在UITableViewDelegate /数据源工具中使用排序后的数组
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCellIdentifier") as? ToDoCell else {
fatalError("Could not dequeue a cell")
}
cell.delegate = self
let jog = sortedArray[indexPath.row] // sorted array
cell.titleLabel?.text = jog.title
cell.descriptionLabel.text = jog.notes
cell.dateLabel.text = Jog.jogDateFormatter.string(from: jog.jogDate)
return cell
}