在使用Cocoa Touch創建具有多個分區的TableView時,需要實現UITableViewDataSource協議中的方法來返回有多個分區的TableView。以下是一個簡單的示例代碼:
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
let data = [["Section 1 Row 1", "Section 1 Row 2", "Section 1 Row 3"],
["Section 2 Row 1", "Section 2 Row 2", "Section 2 Row 3"]]
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: view.bounds)
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = data[indexPath.section][indexPath.row]
return cell
}
}
在上面的代碼中,我們創建了一個包含兩個分區的TableView,并為每個分區提供了一些數據。在numberOfSections
方法中返回了分區的數量,tableView(_:numberOfRowsInSection:)
方法中返回每個分區的行數,tableView(_:cellForRowAt:)
方法中為每個單元格提供數據并顯示。最后,在viewDidLoad
方法中創建了一個TableView并設置其數據源為當前的ViewController。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。