#16 ⭐️實作 Table View 的基本功能 > 特斯拉超級充電站
之前#7 是使用靜態static cell來實作table view,缺點是每一個充電站都需要一個畫面來呈現,此次動態Dynamic prototypes,利用程式只需要一個畫面即可呈現所有充電站的說明,不過還是有缺點,資料內容還是一樣寫在程式裡,之後會把資料寫在雲端,就可以隨時更新資料.
畫面設計
首先建立一個table view controller,再embed in一個navigation controller,此畫面是顯示各地區的充電站,之後再建立一個view controller,來顯示各個充電站的內容
檔案建立
- 新增一個swift file為supercharger
- 其餘三個都是cocoa touch class,如圖下共四個檔案
圖下是supercharger.swift 檔案裡面建立一個 struct 儲存 充電站名字(name)、地址(address)、內容(intro), 用enum分為四個區域
superchatgerTableViewController.swift
為主畫面檔案,主要內容如下
- 建立二層array,分成四個section
- @IBSegueAction func,把資料傳遞到另一個頁面
3. func numberOfSections,計算superchargerStations內有幾筆資料
4. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int),計算arrary有幾個section
5. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath),
(1)superchargercell的identifler需輸入自訂的字串名稱,或是在程式裡建立一個struct之後再輸入文字就可避免輸入錯誤或是修改時只要修改struct內的資料即可
(2)把每筆資料顯示在table view上面,利用 as! 轉變成cell型別,就可以使用outlet
}
let cell = tableView.dequeueReusableCell(withIdentifier: Properkey.superchargercell, for: indexPath) as! superchargerTableViewCell
6.func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int),把每個section內容寫在各個section header
superchatgedetailViewController.swift
為顯示點選到的充電站並跳到另一個頁面顯示其他資料
superchargerTableViewCell.swift
因為cell是動態生成的,每一筆資料都是一個cell,但outlet生成的變數只能存一個元件,所以需要新增一個繼承UITableView的類別,並把outlet拉到此檔案裡,並在tabelView這個畫面cell裡面的content view的class改成superchargerTableViewCell,如下圖