表格(UITableView)
UITableView继承与UIScrollView
- UITableView 有2个代理协议变量,这俩个协议变量非常重要。UITableViewDelegate,UITableViewDataSource 。UITableViewDataSource 的协议变量dataSource用来给TableView提供数据。如果某个类的实类能作为UITableView的dataSource属性,就必须实现UITableViewDataSource协议。UITableViewDelegate的协议变量delegate用来控制UITableView的界面展示和相关的事件响应。
- 表格控件通常展示一列数据,每一列数据的每一行就是一个UITableViewCell,通过改变UITableViewCell实现对UITableView的制定。
- 定义变量
var tableView : UITableView? = nil
- 创建 TableView,并添加在视图上
let frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
self.tableView = UITableView(frame: frame, style: .grouped)
- 分割线颜色
self.tableView?.separatorColor = UIColor.red
self.tableView?.separatorStyle = .singleLine
- 代理:数据源
self.tableView?.delegate = self
//代理:数据源
self.tableView?.dataSource = self
- 每个分组有多少行
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
- 返回都少个分组
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
-
返回头部标题
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return"标题" }
* 头部视图高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
* 返回单元格(每个单元格走一次)reuseIdentifier: "1" :标志符
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: .value1, reuseIdentifier: "1")
cell.imageView?.image = UIImage(named: "1.jpg")
cell.textLabel?.text = "zhangsan"
cell.detailTextLabel?.text = "简介"
return cell
* //设置每一个单元格
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}