Ad

AwakeFromNib Vs DidSet: Where To Set Font Or Corner Radius And Why?

- 1 answer

I am trying to understand the difference between setting the font to a label or cornerRadius to a view in didSet of the outlet of UILabel or UIView vs doing it in awakeFromNib.

Which one is a good practice and why? Is there any performance or compilation-related reason?

@IBOutlet weak var titleLabel: UILabel! {
   didSet {
      titleLabel.font = UIFont
   }
}

vs

override func awakeFromNib() {
   super.awakeFromNib()
   // Initialization code
   titleLabel.font = UIFont
}
Ad

Answer

If you are just setting a simple font:

titleLabel.font = UIFont(name: "SomeFamily", size: 20)

then it doesn't really matter whether you do it in didSet or awakeFromNib. However, if your font depends on the property of some other IBOutlet, like (contrived example here):

titleLabel.font = UIFont(name: anotherLabelOutlet.text!, size: 20)

Then you should definitely do it in awakeFromNib. In awakeFromNib, as it is documented:

When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

In the didSet of titleLabel, however, it is not necessarily true that anotherLabelOutlet has been set. Outlets are set in a non-guaranteed order.

This not only applies to setting fonts, but also any initialisation that involves other outlets.

On the other hand, if you happen to reassigntitleLabel somewhere down the line (for some weird reason), that new label won't get the font you set, if you set it in awakeFromNib, but will if you set it in didSet.

// in a later part of the code...
titleLabel = UILabel(frame: ...)
// titleLabel now has the new font if you set it in didSet, otherwise it won't

I would recommend that you don't think about this too much and just do it in awakeFromNib, and avoid reassigning IBOutlets in general.

Ad
source: stackoverflow.com
Ad