開發環境
- OS X El Capitan
- Xcode 7.0.1
- 語言:Swift 2.x
專案建立與 UI 佈局
- 新建 **Single View Application**,專案名
UITableViewDemo
- Storyboard 中從物件庫拖入 **Table View** 鋪滿全螢幕
- 設定 Table View:
• Prototype Cells = 1
• 選中 Cell → Attributes Inspector → Style = Basic
• Identifier = "Cell"(程式碼會用到)
資料綁定:實作 UITableViewDataSource & Delegate
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let colors = ["Red","Yellow","Green","Gray","Orange","Black","White"]
// MARK: - DataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return colors.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = colors[indexPath.row]
return cell
}
}
關鍵技術點
dequeueReusableCellWithIdentifier:Cell 重用機制,只建立可視區域數量的 Cell,滑動時回收重填資料,極大降低記憶體佔用
- Identifier **必須**與 Storyboard 設定一致
Storyboard 連線:DataSource & Delegate 綁定
- 開啟 **Document Outline**(左側場景樹)
- 按住 Control 拖曳 **Table View** → **View Controller**
- 彈出選單選 **dataSource**
- 重複一次選 **delegate**
執行與進階
- Cmd+R 執行模擬器,即可見七色列表
- 後續可擴展:
• 自訂 Cell(xib 或代碼)
• 分區、索引、編輯模式
• 下拉刷新、無限滾動
原始碼下載
GitHub 完整專案