(Swift) 如何在 TableView 中,結合相同名稱 section 的資料

目的:學習將相同日期的資料合併到同一 section 中

先來看一下 Spending 的資料型別

struct Spending {
var date: Date
var spendingtype: String
var spendingname: String
var paytype: String
var spending: Int
var note: String
}

我們每筆的資料如下

Spending(date: date, spendingtype: sptype, spendingname: spname, paytype: pytype, spending: spending, note: note)

第一步

在想要呈現整理資料的頁面(ListTableViewController)新增兩個變數

class ListTableViewController: UITableViewController {

// 原資料
var list = [Spending]()

// 新資料(本頁顯示資料)
var dic = [String:[Spending]]()
var keys = [String]()

第二步

在 viewDidLoad 中新增以下程式製作新的資料

override func viewDidLoad() {
super.viewDidLoad()
...
// 新資料 設定
dic = Dictionary(grouping: list, by: { formatter.string(from: $0.date)})
keys = Array(dic.keys)
keys.sort(by: <)

dic = [“日期” , [原本的資料(list)]]

keys = [“日期1”, “日期2”, “日期3”]

keys.sort(by: <) 將日期由小到大排列

第三步

設定 row, section 數量以及內容

row 數量

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dic[keys[section]]!.count
}

row 內容

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

cell.textLabel?.text = dic[keys[section]]![row].spendingname
return cell
}

section 數量

override func numberOfSections(in tableView: UITableView) -> Int {

return dic.keys.count
}

section 內容

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {// 判斷 日期內是否還有資料,若沒有資料將回傳 nil
if dic[keys[section]]!.isEmpty {
return nil
}else {
return keys[section]
}
}

做完以上步驟後,進入到列表頁面,就會看到資料已經按照日期整理完畢了

參考文章

--

--