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,0,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
    }

展示如下所示:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值