[編輯] 在我的 fetchData 函式末尾添加這個可以解決問題:
//Sort the tableView by date and time if it's the same date
self.tasks.sort { if $0.date != $1.date {
return $0.date < $1.date
}
else {
return $0.hour < $1.hour
}
}
我剛開始編程,我被卡住了,基本上我有一個顯示多個任務的表格視圖,我想按日期對任務進行排序,所以我提取了任務的時間/小時(已在 firebase 中創建),然后將它們轉換為日期對它們進行排序,但我不知道如何將它們“轉換”回字串以將它們放回我的 cell.date.text ......這就是我到目前為止嘗試的原因:
var convertedArray: [Date] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! MyTasksTableCell
//Gathering the date and hour (string)
let date = "\(Tasks[indexPath.row].date)"
let hour = "\(Tasks[indexPath.row].hour)"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy 'at' HH:mm"
let DateHour = date " at " hour
//OUTPUT:
// 10/22/2021 at 15:10
// 10/21/2021 at 22:24
// 10/21/2021 at 01:55
// 12/16/2021 at 14:50
// Converting them to a Date
let finalDate = dateFormatter.date(from: DateHour)
//OUTPUT:
// Optional(2021-12-16 13:50:00 0000)
// Optional(2021-10-22 13:10:00 0000)
// Optional(2021-10-21 20:24:00 0000)
// Optional(2021-10-20 23:55:00 0000)
//Sorting them
convertedArray.append(finalDate!)
let dateObject = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
//OUTPUT:
// [2021-10-22 13:10:00 0000]
// [2021-10-22 13:10:00 0000, 2021-12-16 13:50:00 0000]
// [2021-10-21 20:24:00 0000, 2021-10-22 13:10:00 0000, 2021-12-16 13:50:00 0000]
// [2021-10-20 23:55:00 0000, 2021-10-21 20:24:00 0000, 2021-10-22 13:10:00 0000, 2021-12-16 13:50:00 0000]
for date in dateObject {
let date = dateFormatter.string(from: date)
//OUTPUT:
// 12/16/2021 at 14:50
// 10/22/2021 at 15:10
// 12/16/2021 at 14:50
// 10/21/2021 at 01:55
// 10/22/2021 at 15:10
// 12/16/2021 at 14:50
// 10/21/2021 at 01:55
// 10/21/2021 at 22:24
// 10/22/2021 at 15:10
// 12/16/2021 at 14:50
}
var newList = [String]()
for date in dateObject {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MM/dd/yyyy 'at' HH:mm"
let convertDate = dateformatter.string(from: date)
newList.append(convertDate)
}
print(newList)
//OUTPUT:
// ["12/16/2021 at 14:50"]
// ["10/22/2021 at 15:10", "12/16/2021 at 14:50"]
// ["10/21/2021 at 22:24", "10/22/2021 at 15:10", "12/16/2021 at 14:50"]
// ["10/21/2021 at 01:55", "10/21/2021 at 22:24", "10/22/2021 at 15:10", "12/16/2021 at 14:50"]
uj5u.com熱心網友回復:
您必須訂購 dataSource(這里是您的 Tasks 陣列)。然后它們將在 TableView 中以正確的順序顯示。
或者您也可以創建一個計算變數orderedTasks 并將其用作您的資料源。
注意:Swift 中的 var 名稱應以小寫開頭,因此請使用任務而不是任務(這適合類或結構命名)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348058.html
