Fred Novack
Fred Novack

Reputation: 811

Can a UIView load another nib after it's initialization?

Just a question to feed my curiosity. Can a UIView after it's initialization with a nib, load another nib again?

For example, this is where I initialize my View with a certain nib:

private func selfInit(){
    Bundle(for: type(of: self)).loadNibNamed(fileName, owner: self, options: nil)
    self.addSubview(contentView)
}

override init(frame: CGRect){
    super.init(frame: frame)
    selfInit()
}

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

can I after the initialization of the nib with Bundle(...) I change the Nib again?

Upvotes: 0

Views: 54

Answers (1)

Ahmad F
Ahmad F

Reputation: 31645

No Doubt that overriding the initializer to setup the initial values for setting default values for the class variables (including the UIViews) would be a good idea, but when it comes to adding a subview I would recommend to do it in the awakeFromNib() method:

Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

Seems to be more appropriate method to add a subview in it; For instance, imagine that subview should has constraints with other components in the main view, you would need to guarantee that all components has been established.

Thus:

override func awakeFromNib() {
    super.awakeFromNib()
    selfInit()
}

Upvotes: 1

Related Questions