Kevin Lieser
Kevin Lieser

Reputation: 977

Swift Custom UITableViewCell with programmatically created UITableView

I'm trying to use a custom TableViewCell Class in my programmatically created UITableView and i can't figure out why this don't get to work. I've used custom TableViewCell Classes a few times without any problems (set the Classname in Storyboard) but here i have no Storyboard to set the Class which should be used to generate the Cells.

I'm doing this:

override func viewDidLoad() {
    ...
    self.popupTableView.registerClass(CustomTableViewCellPopup.self, forCellReuseIdentifier: "popupTableViewCell")
    ...
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("popupTableViewCell") as CustomTableViewCellPopup
    ...
    return cell
}

class CustomTableViewCellPopup: UITableViewCell {

    var message: UILabel = UILabel()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required init(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        println("I'm running!")
        self.message.frame = CGRectMake(0, 0, 10, 10);
        self.message.backgroundColor = UIColor.brownColor()
        self.addSubview(self.message)
    }

}

The println() Output never appears. The TableView gets rendered without the additional UILabel (message). Just like an out of the box UITableViewCell.

The same way (without registerClass()) i'm running a TableView with custom Cells from the Storyboard (the Classname directly defined in the Storyboard Inspector) without any problems.

Have you an idea why the custom Class don't get used?

Upvotes: 9

Views: 11009

Answers (2)

Graham Perks
Graham Perks

Reputation: 23390

You're not seeing the println output because that's in awakeFromNib, which is only called if you cell comes from a storyboard or XIB. Here you're just registering the class with the table, so there's no Nib loading going on. Try making a call to configure the cell from tableView:cellForRowAtIndexPath:, rather than configuring in awakeFromNib.

initWithCoder: won't be called for the same reason - try overriding initWithStyle:reuseIdentifier:.

Upvotes: 3

Cihan Tek
Cihan Tek

Reputation: 5409

awakeFromNib won't get called unless the cell is loaded from a xib or storyboard. Move your custom code from awakeFromNib into initWithStyle:reuseIdentifier: because that's the initializer used by the tableView when you call its dequeueReusableCellWithIdentifier: method

Upvotes: 39

Related Questions