6.1_UITableView基础:创建与数据源
准备好探索UITableView的世界了吗?🎉 这是一个iOS开发中非常重要的组件,用于展示滚动的数据列表。让我们一起学习如何创建和配置它!
创建UITableView
首先,你需要创建一个UITableView的实例。这可以通过编程方式完成,告别Storyboard!💪 你可以在你的ViewController中添加以下代码:
swift
let tableView = UITableView()接下来,你需要将这个tableView添加到你的视图层级中。别忘了设置它的frame,这样它才能正确显示。
swift
tableView.frame = view.bounds // 使用整个屏幕
view.addSubview(tableView)配置UITableView
配置UITableView是让它按照你的意愿显示的关键。你需要设置一些重要的属性,例如背景颜色、分隔线样式等。🎨
swift
tableView.backgroundColor = UIColor.white
tableView.separatorStyle = .singleLine你还可以设置rowHeight属性来调整每一行的高度。
swift
tableView.rowHeight = 60 // 设置行高为60数据源协议
UITableView需要一个数据源来告诉它要显示什么数据。你需要实现UITableViewDataSource协议。这个协议有两个主要的方法:
numberOfRowsInSection(in tableView: UITableView) -> Int: 这个方法告诉tableView有多少行数据。cellForRowAt(indexPath: IndexPath) -> UITableViewCell: 这个方法为每一行创建一个cell。
swift
class MyViewController: UIViewController, UITableViewDataSource {
let data = ["Item 1", "Item 2", "Item 3"] // 示例数据
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count // 返回数据数量
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "MyCell")
cell.textLabel?.text = data[indexPath.row] // 设置cell的文本
return cell
}
}注册数据源
最后,你需要告诉tableView使用你的ViewController作为数据源。
swift
tableView.dataSource = self别忘了在你的ViewController中遵循UITableViewDataSource协议!✅
示例:简单的数据列表
让我们创建一个简单的例子,展示一个包含三个项目的列表。
swift
import UIKit
class MyViewController: UIViewController, UITableViewDataSource {
let tableView = UITableView()
let data = ["苹果", "香蕉", "橙子"] // 水果列表 🍎🍌🍊
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
tableView.frame = view.bounds
tableView.dataSource = self
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "MyCell")
cell.textLabel?.text = data[indexPath.row]
return cell
}
}现在,运行你的应用,你应该能看到一个包含三个水果名称的列表!🎉 恭喜你,你已经成功创建并配置了一个UITableView!