當 UITableView 的資料量很大,例如幾百筆以上的清單,右側索引能讓使用者快速跳到指定分區。實作時,通常會準備一個索引陣列,以及各 section 的資料陣列。
範例以 A 到 O 分成三組,分別放入 dataArray1、dataArray2、dataArray3。indexArray 則保存 section 標題。表格方法會依 section 與 row 取得對應文字,讓畫面呈現分組效果。
sectionIndexTitlesForTableView: 回傳索引;titleForHeaderInSection: 設定區段標題;numberOfSectionsInTableView: 決定 section 數量;numberOfRowsInSection: 回傳各 section 的列數;cellForRowAtIndexPath: 則設定每個儲存格內容。完成這些方法後,就能建立可點擊索引的表格。
這個做法適合資料分組明確的情境。若資料需要動態本地化排序,則可進一步改用 UILocalizedIndexedCollation。