iOS Dev. Lesson 7

Makzan, updated 2021 May.

Agenda

  • Tab Bar x Navigation x Table View Controller
  • Table View Controller

Tab Bar Controller

Tab Bar Controller Basic

Table View Controller

The most important view controller in iOS development.

我們必須學懂用 Delegate。

要用好Table View Controller

Table View 是 iOS 負責 Render 的。

What is a delegate?

UITableView 的構建及顯示(Rendering)是系統負責的,這樣可以確保 UITableView 的渲染符合 iOS 的速度要求。

要使用 UITableViewController,必須了解其 Delegate Protocol:

UITableViewDelegateUITableViewSource

Table View Data Source

DataSource 是連接 UITableView 及數據的專用 Protocol。

內有最重要的 3 個函數

  • Number of sections
  • Number of rows in section
  • Cell for Table View at Index Path

Number of sections

第一個問題,預設答案是 1 個Section。Section 即是分類,例如將聯絡列表分開成 A-Z 26 個分類等。

Number of rows in section

第二個問題,會因應有多少個 Section 便會問我們多少次,逐個逐個 Section 問我們這個分組內有多少個Row。

通過解答此三個問題,iOS便懂得如何製作及顯示我們的 UITableView。

  • Number of sections
  • Number of rows in section
  • Cell for Table View at Index Path

話說,這個返回數字不須要 Hard Code。可以因應情況改變,例如如果列出Profile 時,有分 VIP 及 非 VIP 兩種帳號,則有可能他們顯示的 Profile 個人帳號資料列表有不同的 Row 行數

  • Number of sections
  • Number of rows in section
  • Cell for Table View at Index Path

Cell for Table View at Index Path

至於第三個問題,

IndexPath 是記錄低哪個 Section 哪個 Row,

所以這個函數就是在問某一個 Section 某一個 Row 的那個介面,在 UITableView 中,一行的介面是 UITableViewCell。

某一個 Section 某一個 Row

為何我說某一?因為系統會自動處理整個列表的顯示,所以,如果用戶滑動列表到途中某位置時,系統便會突然需要某一個的資料及如何顯示的介面設定。 要用好這個函數,可以分為兩個階段:

  • ReuseIdentifier
  • 準備要 Return 的 Cell

ReuseIdentifier

一個基本的 UITableView,只需要一個 reuse identifier,意即只有一種類的 UITableViewCell。

準備 Cell Return

拿出可以重用的 UITableViewCell 後,我們就要因應這個 Section 這個 Row 須要的界面,換上內容及設定好當中倘有的 UIView。

UITableViewAccessory

預設的 UITableViewCell 右方有個 Accessory,這個位置預設有 4 種方式:

  • Checkmark
  • Disclosure Indicator
  • Info button
  • Disclosure Info Button

iOS Dev. Lesson 7

By makzan

iOS Dev. Lesson 7

  • 224