swift中实现UITableView总结二
上一篇总结了一下UITableView的简单实现,但自带的UITableView的往往不能满足于我们的需求,所以很多时候都需要我们自定义cell,下面就简单的总结下自定义UiTableViewCell的步骤: 总所周知,在ios8以后UITableViewCell的分割线左边就会有间隙,往往很多需求却是要补全的,所以在自定义的cell里面可以设置: 首先:建立一个类,集成UiTableViewCell,当然需要实现他们的构造方法,重写drawRect方法,实现如下: /** * 自定义cell分割线 */ override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context,UIColor.clearColor().CGColor) CGContextFillRect(context,rect) //下分割线 CGContextSetStrokeColorWithColor(context,UIColor.grayColor().CGColor) CGContextStrokeRect(context,CGRectMake(0,rect.size.height,rect.size.width,1)) } 当然如果需要重新修改Cell的样式需要在初始化方法里面,如下所示: override init(style: UITableViewCellStyle,reuseIdentifier: String?) { super.init(style: style,reuseIdentifier: reuseIdentifier) //初始化UILabel label = UILabel(frame: CGRectMake(self.frame.size.width-100,100,self.frame.size.height)) label?.textColor = UIColor.redColor() label?.textAlignment = NSTextAlignment.Center label?.font = UIFont.systemFontOfSize(15.0) self.contentView.addSubview(label!) } 在UiTableViewCell中操作完了,接下来就需要在调用这个cell的类里面操作的: 在初始化UITableView的地方,需要注册cell的类,如下所示 tableView?.registerClass(TableViewCell.self,forCellReuseIdentifier: "CELL") 之前在cell里面重绘了cell的分割线,所以在实现的地方,你需要先去除系统自带的分割线 tableView?.separatorStyle = UITableViewCellSeparatorStyle.None 最后就是在你需要展示数据的方法里面实现自定义cell的类,如下所示: /** * 显示数据源的数据方法 */ func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CELL") as! TableViewCell // if cell == nil{ // // cell = UITableViewCell(style: .Default,reuseIdentifier: "CELL") // } let row = indexPath.row cell.selectionStyle = UITableViewCellSelectionStyle.None cell.textLabel?.text = items![row] as? String cell.label?.text = focus![row] as? String return cell } 展示如下所示:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |