“`html

Swift 表格式畫面 (UITableView) – 2025 最新教學與最佳實踐 📊

Swift 表格式畫面 (UITableView) 是 iOS 開發中最常見的畫面之一,能夠幫助開發者快速建立表格式的界面,讓使用者更輕鬆地閱讀資料。本文將深入探討如何使用 Swift 來建立 UITableView,並提供全面的程式碼範例及實作細節,以幫助開發者快速上手。

建立 UITableView

要建立 UITableView,首先需要在 Storyboard 中新增一個 UITableView,並將其拖曳至 ViewController 中。接著,將 UITableView 的 delegate 和 dataSource 連接到 ViewController,具體步驟如下:

UITableView 連接示意圖

設定 ViewController

在 ViewController 中,我們需要實作 UITableViewDelegate 和 UITableViewDataSource 方法,以讓 UITableView 正確顯示資料。以下是基本的程式碼範例:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 返回要顯示的行數
        return data.count // 假設有一個資料陣列
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 返回要顯示的 cell
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = data[indexPath.row] // 假設資料是字串
        return cell
    }
}

設定 UITableViewCell

cellForRowAt 方法中,我們使用 dequeueReusableCell 方法來取得可重複使用的 cell,並設定其內容。請參考以下程式碼:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    // 設定 cell 的內容
    cell.textLabel?.text = "行數:\(indexPath.row + 1)" // 範例內容
    return cell
}

錯誤排除

在使用 UITableView 時,常見的錯誤包括:

  • 未連接 delegate 和 dataSource:確保在 Storyboard 中正確連接。
  • cell 標識符錯誤:檢查在 Storyboard 中設定的標識符是否與程式碼中一致。
  • 返回行數為零:確保 numberOfRowsInSection 方法返回正確的行數。

延伸應用

除了基本的 UITableView 應用,您還可以擴展如下功能:

  • 多個 section 的 UITableView。
  • 自定義 UITableViewCell 的樣式。
  • 使用 SwiftUI 來建立表格式畫面。

總結

在本文中,我們介紹了如何使用 Swift 來建立 UITableView,並提供了範例程式碼及實作步驟。無論您是新手還是經驗豐富的開發者,這些知識都能幫助您快速開發出表格式的畫面。

Q&A(常見問題解答)

Q1:如何在 UITableView 中添加圖片?

A1:您可以在 cellForRowAt 方法中,使用 cell.imageView?.image = UIImage(named: "imageName") 來設定圖片。

Q2:UITableView 和 UICollectionView 有什麼區別?

A2:UITableView 是用於顯示單一列的資料,而 UICollectionView 可以用於顯示多種排列方式的資料,如網格。

Q3:如何實現 UITableView 的刪除功能?

A3:您可以使用 tableView.deleteRows(at:with:) 方法來刪除指定的行,並在資料源中更新相應的資料。

Swift 表格式畫面 (UITableView) 📊
“`

Categorized in:

Tagged in:

,