2

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

Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
  • 1
    if you don't use xib or story board I think awakeFromNib is useless. – Nekak Kinich May 27 '15 at 17:48
  • 1
    And, worse, you're instantiating two different `UILabel` objects, so when `awakeFromNib` is not called, the other `UILabel` object will be found (even though it was never added to any `containerView`). – Rob May 27 '15 at 17:50
  • Also, if you register a class for a reuse identifier, then `cell` will never be `nil`, so you can simplify `cellForRowAtIndexPath`. – Rob May 27 '15 at 17:51

1 Answers1

9

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

Amit89
  • 3,000
  • 1
  • 19
  • 27