(Swift) 如何在 TableView 中,顯示指定 section 的資料
Published in
4 min readJul 10, 2022
目的:顯示指定月份的資料
在上一篇中,有提到 如何將同樣日期的資料結合在一起,現在將會將資料再次整理,抓出選擇月份的資料
第一步
在想要呈現整理資料的頁面(ListTableViewController)新增1個變數
class ListTableViewController: UITableViewController {
// 原資料
var list = [Spending]()
// 新資料(本頁顯示資料)
var dic = [String:[Spending]]()
var keys = [String]() // 指定的日期
let assigneddate: Date? ....
assigneddate 會存取前一頁所選擇的日期
第二步
在 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) 新增以下程式碼
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 判斷 是否為指定的日期,若不是將回傳 0
if keys[section].contains(formatter.string(from: assigneddate!)) {
return dic[keys[section]]!.count
}
return 0
}
contains 會判斷 keys 中是否有符合 assigneddate 指定的日期,若有符合會回傳 row 的數量
第三步
在 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) 新增以下程式碼
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // 判斷 日期內是否還有資料,若沒有資料將回傳 nil
if dic[keys[section]]!.isEmpty {
return nil
}
// 判斷 是否為指定的日期,若不是將回傳 nil
if keys[section].contains(formatter.string(from: assigneddate!)) {
return keys[section]
}else {
return nil
}
}
contains 會判斷 keys 中是否有符合 assigneddate 指定的日期,若有符合會回傳 row 的內容
做完以上的幾步驟,即可成功將所擇的日期顯示在指定的頁面中