0
votes

I am created a custom UITableViewCell and added some outlet fields which connect to the UI elements on storyboard. Please see below as an example. But I always got nil pointer exception on the line "self.skillBtn.backgroundColor = UIColor.redColor()" in "required init?(coder aDecoder: NSCoder) " method. It means that the skillBtn has not been initialized yet. I wander where I should do the UI initialization on a UITableViewCell?

@IBOutlet weak var backgroundImg: UIImageView!

@IBOutlet weak var userNameLabel: UILabel!

var delegate: UserHomeCategorySelectionDelegate?

@IBOutlet weak var skillBtn: UserHomeCategoryButton!

@IBOutlet weak var speakBtn: UserHomeCategoryButton!

@IBOutlet weak var friendsBtn: UserHomeCategoryButton!


override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.skillBtn.backgroundColor = UIColor.redColor()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.skillBtn.backgroundColor = UIColor.redColor()

}
1

1 Answers

1
votes

Thats because the views are not yet connected from your Storyboard/XIB to your class instance,

to achieve what you want, override awakeFromNib method and put self.skillBtn.backgroundColor = UIColor.redColor() inside it.

awakeFromNib is called after view is loaded from the XIB/Storyboard and outlets are connected.