swift

UITableView
- UITableView继承于UIScrollView
- UITableView的每一条数据对应的单元格叫cell,是UITableView的一个对象,继承于uiview
- UITableView可以分区显示,每个分区为section
- UITableView的每一行叫做raw

-
定义一个UITableView的变量
<pre>
var tableView : UITableView? = nil
</pre> -
初始化frame的值
<pre>
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: .plain)
self.view.addSubview(tableView!)
</pre>
- 要实现UITableView中的方法,必须写delegate、dataSource
<pre>
self.tableView?.delegate = self
self.tableView?.dataSource = self
</pre>
- 要写方法之前,ViewController要继承UITableViewDelegate,UITableViewDataSource
- 这时我们发现报错了,要把UITableViewDataSource的两个方法实现一下
<pre>
//每个分组有多少行
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 10
}
//返回单元格(每个单元格走一次)
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//初始化单元格
let cell = UITableViewCell(style: .default, reuseIdentifier: "1")
return cell
}
</pre>
- 这时的cell没有显示内容,我们要在返回单元格的方法中添加内容
<pre>
cell.imageView?.image = UIImage(named: "1")
cell.textLabel?.text = "zhangsan"
cell.detailTextLabel?.text = "简介"
</pre>
- 显示结果:

- 设置分组
- 要把self.tableView = UITableView(frame: frame, style: .plain)中的样式改为.grouped
<pre>
//返回多少分组
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
</pre>
- 显示单元格的行高
<pre>
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
</pre>
- 返回头部标题
<pre>
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "标题"
}
</pre>
- 返回头部视图的高度
<pre>
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
</pre>
- 显示结果:


年轻,就要有上路的渴望,要与勇敢同行。被动承受,不如勇敢地面对;鸟宿檐下,不如击翅风雨;卓越是勇敢的成果。你不勇敢,没人替你坚强,能战胜束缚自己的心魔,才是真正的勇敢者。有时勇敢不利于思考,但有利于实干,所以,毅力智慧谦虚与平凡是真正勇敢者的尺度。
网友评论