swift中实现UITableView总结二

前端之家收集整理的这篇文章主要介绍了swift中实现UITableView总结二前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

上一篇总结了一下UITableView的简单实现,但自带的UITableView的往往不能满足于我们的需求,所以很多时候都需要我们自定义cell,下面就简单的总结下自定义UiTableViewCell的步骤

总所周知,在ios8以后UITableViewCell的分割线左边就会有间隙,往往很多需求却是要补全的,所以在自定义的cell里面可以设置:

首先:建立一个类,集成UiTableViewCell,当然需要实现他们的构造方法,重写drawRect方法,实现如下:

  1. /**
  2. * 自定义cell分割线
  3. */
  4. override func drawRect(rect: CGRect) {
  5. let context = UIGraphicsGetCurrentContext()
  6. CGContextSetFillColorWithColor(context,UIColor.clearColor().CGColor)
  7. CGContextFillRect(context,rect)
  8. //下分割线
  9. CGContextSetStrokeColorWithColor(context,UIColor.grayColor().CGColor)
  10. CGContextStrokeRect(context,CGRectMake(0,rect.size.height,rect.size.width,1))
  11. }

当然如果需要重新修改Cell的样式需要在初始化方法里面,如下所示:
  1. override init(style: UITableViewCellStyle,reuseIdentifier: String?) {
  2. super.init(style: style,reuseIdentifier: reuseIdentifier)
  3. //初始化UILabel
  4. label = UILabel(frame: CGRectMake(self.frame.size.width-100,100,self.frame.size.height))
  5. label?.textColor = UIColor.redColor()
  6. label?.textAlignment = NSTextAlignment.Center
  7. label?.font = UIFont.systemFontOfSize(15.0)
  8. self.contentView.addSubview(label!)
  9. }

在UiTableViewCell中操作完了,接下来就需要在调用这个cell的类里面操作的:

在初始化UITableView的地方,需要注册cell的类,如下所示

tableView?.registerClass(TableViewCell.self,forCellReuseIdentifier: "CELL")

之前在cell里面重绘了cell的分割线,所以在实现的地方,你需要先去除系统自带的分割线

tableView?.separatorStyle = UITableViewCellSeparatorStyle.None

最后就是在你需要展示数据的方法里面实现自定义cell的类,如下所示:

  1. /**
  2. * 显示数据源的数据方法
  3. */
  4. func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  5. let cell = tableView.dequeueReusableCellWithIdentifier("CELL") as! TableViewCell
  6. // if cell == nil{
  7. //
  8. // cell = UITableViewCell(style: .Default,reuseIdentifier: "CELL")
  9. // }
  10. let row = indexPath.row
  11. cell.selectionStyle = UITableViewCellSelectionStyle.None
  12. cell.textLabel?.text = items![row] as? String
  13. cell.label?.text = focus![row] as? String
  14. return cell
  15. }

展示如下所示:

猜你在找的Swift相关文章