首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Swift 開發 iOS 應用入門(一):UITableView 列表完整實作教學

     編輯:Java 綜合教學

開發環境

  • OS X El Capitan
  • Xcode 7.0.1
  • 語言:Swift 2.x

專案建立與 UI 佈局

  1. 新建 **Single View Application**,專案名 UITableViewDemo
  2. Storyboard 中從物件庫拖入 **Table View** 鋪滿全螢幕
  3. 設定 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 綁定

  1. 開啟 **Document Outline**(左側場景樹)
  2. 按住 Control 拖曳 **Table View** → **View Controller**
  3. 彈出選單選 **dataSource**
  4. 重複一次選 **delegate**

執行與進階

  • Cmd+R 執行模擬器,即可見七色列表
  • 後續可擴展:
     • 自訂 Cell(xib 或代碼)
     • 分區、索引、編輯模式
     • 下拉刷新、無限滾動

原始碼下載

GitHub 完整專案

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved