Custom TableViewCell without storyboard

对着背影说爱祢 提交于 2019-12-21 22:27:16

问题


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.

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!
    }

and my cell class looks like

    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)
    }

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


回答1:


Do this way.

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)
    }

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

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

Set these two delegate - UITableViewDataSource and UITableViewDelegate



来源:https://stackoverflow.com/questions/30489496/custom-tableviewcell-without-storyboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!