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
    }

展示如下所示:

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...