#51 實作 Table View 的基本功能
目的: 學習實作表格的基本功能和定義 UITableViewDataSource 的相關 function。
利用表格顯示清單,比方電影列表,音樂列表,App 列表,可找一個現成的 App 模仿,比方 App Store,Music,FB,IG,Medium,LINE。
基本題
使用 table view controller,實現以下功能
- 利用內建的 cell 樣式顯示表格內容。
定義 UITableViewDataSource 的相關 function。
array 的成員型別是自訂型別,比方 struct Song。如果懶得自己輸入 array,也可參考以下連結用 ChatGPT 生出 array。
2. 點選 cell 後可到下一頁顯示詳細資訊。
- 做法 1: 利用 IBSegueAction
- 做法 2: 利用 function prepare
3 多個 section。
參考 Develop in Swift Data Collections 1.5 Table Views 的 Lab Meal Tracker。
進階題
4. 採用以下連結的方法傳入 cell id
5. 客製 cell 顯示表格的內容。
自訂 cell 類別和連結 outlet 到 cell 類別,可考慮以下 2 種寫法
- cell 搭配 as? 轉型,結合 guard let。
- cell 搭配 as! 轉型
6. cell 採用固定高度。
7. cell 類別裡定義設定內容的 function,比方以下例子。
func update(with lover: Lover) {
nameLabel.text = lover.name
photoImageView.image = UIImage(named: lover.imageName)
}
8. 使用 view controller,在 view controller 上另外加入 table view。
9. 在表格上顯示不同的 cell 樣式,搭配不同的 cell id。比方顯示交往過的十二星座情人,每個星座的情人是不同的 cell id。
更進階題
10. cell 搭配 auto layout 自動計算高度。