上一篇总结了一下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 }
展示如下所示:
原文地址:https://www.jb51.cc/swift/325067.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。