swift UITableView(三)

来源:互联网 发布:office办公软件 编辑:程序博客网 时间:2024/06/06 03:56

我们上一节主要讲了简单创建一个表格填充一些数据

继续使用上节代码(代码下载方式见第二节末尾)

这节我们实现两个功能

1,调整每一行的高度

上一节的代码结果我们发现每一行的高度有些显小,文字有点挤在一起了。

tableView有一个代理方法专门用来设置行高

首先我们让ViewController实现一个协议

UITableViewDelegate

设置tableView的delegate

[html] view plaincopy
  1. _tableView.delegate=self  

实现一个协议方法

[html] view plaincopy
  1. func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {  
  2.     return 55  
  3. }  

此处时我们会发现行高比之前提高了


如果细心我们还能发现这个方法有一个参数

NSIndexPath

有了他我们还可以设置指定行的高度

比如我们吧首行高度设置为100 其他的继续为55

[html] view plaincopy
  1. func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {  
  2.       
  3.     if indexPath.row==0{  
  4.         return 100  
  5.     }else{  
  6.         return 55  
  7.     }  
  8.       
  9. }  
效果如下

2.我们经常会见到表格为了看的清楚会隔行设置颜色(比如:奇数行一种颜色,偶数行一种颜色)

我们使用一种方式来设置一下

首先,我们回头看一下方法

[html] view plaincopy
  1. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell  
他里面我们设置标题,副标题等等之前都先创建一个了cell 我们看到 cell是 UITableViewCell类型的 在看这个UITableViewCell发现他就是一个UIView 的子类,而且cell上有一个专门用来现实内容的视图contentView ,其实,刚才我们设置的标题,副标题等等都在contentView上。此时就可以通过设置contentView的背景色实现我们的需求

看代码

[html] view plaincopy
  1. //设置每一行的背景色  
  2. if indexPath.row%2==0{  
  3.     cell?.contentView.backgroundColor=UIColor.whiteColor()  
  4. }else{  
  5.     cell?.contentView.backgroundColor=UIColor.blueColor()  
  6. }  

效果如下:


0 0
原创粉丝点击