Search code examples
swiftuiviewxib

Cannot create a custom view using Xib file due to nil subviews


I have a XIB file with 5 subviews. The XIB is set to a custom class like so

class Slide: UIView {

    @IBOutlet weak var descriptionImage: UIImageView!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var hiLabel: UILabel!
    @IBOutlet weak var loLabel: UILabel!
    @IBOutlet weak var humidityLabel: UILabel!

}

I instantiate like so let slide = Slide()

When I try to set the variables ie slide.descriptionLabel = "Hello"

I get error

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

The stack trace shows that the XIB is instantiated, but the subviews are nil, and, therefore, cannot be set.


Solution

  • It's because you have to load the nib file ( here i suppose nib name is Slide )

    let slide  = Bundle.main.loadNibNamed("Slide", owner: nil, options: nil)![0] as! Slide
    

    as this

    let slide = Slide()
    

    loads the view without it's layout so all attached views are nil