skyguy skyguy - 3 months ago 22
iOS Question

Swift: can't configure custom table cell programmatically? Init not called?

Alright, I am trying to add content to my custom tableview cell programmatically as demonstrated in mob last question here - Swift: tableview cell content is added again and again with each reload? initializing all the content in func tableView() results in overlapping.

I have followed this question verbatim Swift. Proper initialization of UITableViewCell hierarchy And in my custom cell class (which I give a name to in my storyboard) I have:

class EventTableCellTableViewCell: UITableViewCell {


override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier) // the common code is executed in this super call
// code unique to CellOne goes here
print("INIT")
self.contentView.backgroundColor = UIColor.blackColor()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

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

}


And this init is not called because nothing is printed. The errors come in my func tableView() in my main VC. I originally had:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventTableCellTableViewCell
// cell.eventTitle.text = names[indexPath.row]
// cell.eventDescription.text = descriptions[indexPath.row]

cell.contentView.clipsToBounds = false

//cell UIX
let eventTitleLabel = UILabel()
let dateLabel = UILabel()
let authorLabel = UILabel()
let locationLabel = UILabel()

let categoryView = UIImageView()
//then I add everything


But this didn't work so I looked at other posts and now have:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

//var cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventTableCellTableViewCell

var cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! UITableViewCell
if (cell == nil) {
cell = EventTableCellTableViewCell.init(style: .Default, reuseIdentifier: "eventCell")
}


I have also tried doing it without the indexPath. Right now I get an error that cell cannot == nil, and not matter what I write init is not called.

How can I configure my cell programmatically?

Answer

If the cell is designed in the storyboard only init?(coder aDecoder: NSCoder) is called, init(style: style, reuseIdentifier: is never called.

And you have to set the class of the cell in Interface Builder to EventTableCellTableViewCell.