UITableView

Trista's APP quest
6 min readFeb 5, 2021

--

使用 myTableView.register(UITableViewCell.self, forCellReuseIdentifier: “Cell”) 註冊 reuse 的 cell ,辨識名稱設為”Cell”,讓後續顯示時可以使用。因為當 cell 數量超過一個畫面可顯示時,目前存在的 cell 只有畫面上的這些,當上下滑動時,會隨顯示畫面的不同同時移出並加入 cell,不是一直建立新的 cell 而是會重複使用( reuse )。

使用 tableView.dequeueReusableCell(withIdentifier: “Cell”, for: indexPath) as UITableViewCell ,將註冊的 cell 使用的辨識名稱”Cell”,告訴程式要使用哪一個 cell 來重複使用,以取得 UITableView 目前使用的 cell

•UITableView 設置委任模式的對象self:ViewController ,實作委任對象需要的方法,來完善這個表格的內容。UITableView 委任的方法大多會有indexPath參數,這個參數有section及row兩個屬性,表示目前要設置的 cell 是屬於哪一組( section )的哪一列( row ),型別都為 Int 且都是由 0 開始算起
實作 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell,設置UITableView每個 cell 要顯示的內容當 cell 點選變成 highlighted 時,cell 上的UIImageView 會自動變成 highlighted,使用 cell.imageView?.image = UIImage(named: “02.jpg”)設置UIImage外,再使用 cell.imageView?.highlightedImage = UIImage(named: “03.jpg”)設置highlighted 狀態時的UIImage,cell 點選後可顯示於cell上

— 實作 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath),設置UITableView點選 cell 後執行的動作
使用 tableView.deselectRow(at: indexPath as IndexPath, animated: true),設定取消 cell 的選取狀態
使用 tableView.selectRow(at: indexPath as IndexPath, animated: true, scrollPosition: UITableView.ScrollPosition.middle),設定cell 可選取狀態

實作 func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath),設置UITableView點選 Accessory 按鈕後執行的動作

UITableView 點選cell上的文字及點選 Accessory 按鈕後,將選取的結果印出來。點選cell 上的UIImageView 會改顯示 highlighted 狀態的 UIImageView

使用 UITableView 屬性 isEditing判斷是否處於編輯模式,使用 func setEditing(_ editing: Bool, animated: Bool)方法來切換
第一個傳入參數 editing:true 則進入編輯模式
第二個傳入參數 animate:false 則無切換編輯模式的動畫

使用 UITableView 的 beginUpdates()與 endUpdates()方法,中間可使用 func insertRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) 新增一筆資料。中間也可使用 func deleteRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) 刪除一筆資料。

•UITableView 的編輯模式,設置UITableView 的委任對象self:ViewController,ViewController遵守委任需要的協定 UITableViewDelegate和UITableViewDataSource,實作相關的委任方法
實作 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool ,設置UITableView每筆 row 是否可以進入編輯模式,可以根據 indexPath 讓特定的section 的 row 不能編輯。

—實作 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath),編輯模式時拖曳切換 cell 位置後執行動作,實作委任方法出現排序功能。

— 實作 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath),編輯模式時按下刪除 cell 後執行動作,實作委任方法出現左滑刪除功能。

刪除內建的 Main.Storyboard ,在SceneDelegate類別手動建立一個 UIWindow,將self.window的rootViewController設為UINavigationController。於編輯模式切換函式一併設置導覽列左邊及右邊按鈕,實作UITableView委任方法,完成UITableView 的編輯模式。

--

--