我们上一节主要讲了简单创建一个表格填充一些数据
继续使用上节代码(代码下载方式见第二节末尾)
这节我们实现两个功能
1,调整每一行的高度
上一节的代码结果我们发现每一行的高度有些显小,文字有点挤在一起了。
tableView有一个代理方法专门用来设置行高
首先我们让ViewController实现一个协议
UITableViewDelegate
设置tableView的delegate
- _tableView.delegate=self
实现一个协议方法
- func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
- return 55
- }
此处时我们会发现行高比之前提高了
如果细心我们还能发现这个方法有一个参数
NSIndexPath
有了他我们还可以设置指定行的高度
比如我们吧首行高度设置为100 其他的继续为55
- func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
- if indexPath.row==0{
- return 100
- }else{
- return 55
- }
- }
2.我们经常会见到表格为了看的清楚会隔行设置颜色(比如:奇数行一种颜色,偶数行一种颜色)
我们使用一种方式来设置一下
首先,我们回头看一下方法
- func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
看代码
- //设置每一行的背景色
- if indexPath.row%2==0{
- cell?.contentView.backgroundColor=UIColor.whiteColor()
- }else{
- cell?.contentView.backgroundColor=UIColor.blueColor()
- }
效果如下: