實作 Table View 基本功能

UITableViewDataSource, 客製 cell, as, guard let, IBSegueAction

--

成品:恭喜許富凱終於得到金曲歌王頭銜啦~~~

▲主題決定很快但做超久~因為一直瘋狂聽歌不專心 XDD
▲設定 10 首,可是好歌太多一整個難挑到不行呀 >_<
▲本想仿 Youtube 但懶了… 科科
▲參考來源:彼得學姊

前置作業

▲初始 TableViewController + Navigation + ViewController (WebView)
▲新增 Swift File * 1 + Cocoa Touch Class * 3 ,取名後各自配好
▲ TableViewController 選 Dynamic,不要分線 Separator 調 None
▲ cell 手動調整高度或 inspector 取消自動寫數值皆可
➞確定要固定高度可至 TableView 改 Row Height,Estimate 值
▲ cell 選 Custom 後加 ImageView 與 Label,全用 AutoLayout 才可固定
▲ cell Identifier 取名,因不想點 cell 時有顏色,Selection 調 None
▲ cell 拉 Segue 至 ViewController,一開始非從 cell 拉結果沒反應

struct定義 Song 型別並寫其 Array 於 TableViewController

TableViewController 是 TableView 的 dataSource

其 function下面都有註解呈灰色可自由選擇使用

▲ Section 及 Row 預設為 0 呈空白,須自行調整
▲ Section 數量 func 為 optional ,不定義便為 1 個 Section
▲ cell 的數量等於 songs array 數量,只有 1 行其實 return 可省

SongTableViewCell.swift:拉 IBOutlet 及定義 update

回 SongTableViewController.swift

▲cell Id 定義成常數,避免之後打錯字,其餘方法請參考彼得教學

▲ guard let 判斷 optional 是否有值和讀取它的內容,彼得教學
▲ dequeueReusableCell 是產生 cell 的 function
➞為顯示下行 cell,將上端即將消失 cell 移除給下行重複使用
➞ cell ID 如和之前 inspector 設定不同會閃退請注意
➞ indexPath = cell 位置 (section & row),一定有值
▲用 as? 轉型成 cell 的型別後便可存取它的 outlet
▲設定 cell 有很多方法,此為呼叫 cell update func 並將 song 當參數傳入
➞ 如 cell 使用內建樣式非客制,iOS 15 寫法請參考彼得教學

WebViewController:頁面間資料傳遞

▲定義 init,由參數設定 property
▲寫完出現紅色修正屬正常,按 fix 自動有 required initializert

回 SongTableViewController.swift:拉 IBSegueAction

▲ indexPathForSelectedRow
➞ TableView 的 property,型別為 IndexPath?
➞代表目前被選取的 cell 的 index path

WebViewController:加入函式庫,拉 IBOutlet,載入網頁

完整程式碼

Song.swif,SongTableViewController

SongTableViewCell,WebViewController

--

--