以编程方式创建分组样式的UITableView,可以通过以下步骤实现:
以下是一个简单的示例代码:
import UIKit
class GroupedTableViewController: UITableViewController {
let sections = ["Section 1", "Section 2", "Section 3"]
let items = [["Item 1", "Item 2", "Item 3"], ["Item 1", "Item 2", "Item 3"], ["Item 1", "Item 2", "Item 3"]]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = items[indexPath.section][indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return "Section Footer"
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected item: \(items[indexPath.section][indexPath.row])")
}
}
这个示例代码创建了一个分组样式的UITableView,其中包含3个分组,每个分组中有3个单元格。每个单元格的内容是一个字符串,当单元格被选中时,会在控制台中打印出被选中的单元格的内容。
领取专属 10元无门槛券
手把手带您无忧上云