没有故事板的自定义 TableViewCell [英] Custom TableViewCell without storyboard

查看:31
本文介绍了没有故事板的自定义 TableViewCell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用从 TableViewCell 扩展的自定义可可类,它没有给出任何错误消息,但单元格没有出现在 tableview 中.滚动变长但表格单元格不可见.

I am using custom cocoa class extends from TableViewCell and it doesn't give any error message but the cells do not appear in the tableview. The scroll gets longer but the table cells are not viewable.

我在我的 ViewController 中输入:

I typed this in my ViewController :

tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "Cell")

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)->UITableViewCell
    {
        var cell:CustomTableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? CustomTableViewCell
        if cell == nil {
            cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
         }

        cell!.labTime.text = filtered[indexPath.row].name!
        return cell!
    }

我的单元格类看起来像

    var labTime = UILabel()

    override func awakeFromNib() {
        // Initialization code
        super.awakeFromNib()

        labTime = UILabel(frame: contentView.bounds)
        labTime.font = UIFont(name:"HelveticaNeue-Bold", size: 16)

        contentView.addSubview(labTime)
    }

我不使用任何 storyBoard 或 xib 文件.找不到解决办法,谢谢

I don't use any storyBoard or xib file. Can not find the solution, thanks

推荐答案

这样做.

属性的所有视图初始化都应该在 init 方法中.将此添加到您的自定义单元格类中

All view intialization of properties should go in init method. Add this in your custom cell class

var labTime: UILabel!

required init(coder aDecoder: NSCoder) {

            super.init(coder: aDecoder)
    }


    override init(style: UITableViewCellStyle, reuseIdentifier: String!) {

         super.init(style: style, reuseIdentifier: reuseIdentifier)
         //Do your cell set up

        labTime = UILabel(frame: contentView.bounds)
        labTime.font = UIFont(name:"HelveticaNeue-Bold", size: 16)

        contentView.addSubview(labTime)
    }

在视图控制器的 viewDidLoad 方法中添加以下行.

Add the below line in viewDidLoad method of your view controller.

tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "Cell")

设置这两个委托 - UITableViewDataSourceUITableViewDelegate

Set these two delegate - UITableViewDataSource and UITableViewDelegate

这篇关于没有故事板的自定义 TableViewCell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆