Aaron Bratcher
Aaron Bratcher

Reputation: 6451

UIView subview's elements not accessible

I have a plain UIViewController class. At the top of the view, I have a subview that is set to a custom class called HeaderView. I am trying to use an XIB to define the elements of that custom view and loading it in as the controller loads as follows:

@IBOutlet weak var headerView: HeaderView!

override func viewDidLoad() {
    super.viewDidLoad()
    if let view = NSBundle.mainBundle().loadNibNamed("HeaderView", owner: self, options: nil)[0] as? HeaderView {
        self.headerView.addSubview(view)
    }
}

This seems to work as the view as described in the XIB is visible when the main view is shown. However when I try to access the elements inside the subview, the app crashes.

override func viewDidAppear(animated: Bool) {
    headerView.headerLabel.text = "Success!"   // Crash here
}

Example project here: https://github.com/AaronBratcher/ViewTester

This technique works when specifying the header view of a section in a UITableView.

What am I missing?

Upvotes: 0

Views: 823

Answers (1)

Guilherme
Guilherme

Reputation: 7949

if let view = NSBundle.mainBundle().loadNibNamed("HeaderView", owner: self, options: nil)[0] as? HeaderView {
    self.headerView.addSubview(view)
}

In this piece of code, you are adding a subview to a nil HeaderView property. This is not correct. You need to instantiate HeaderView object and assign it to you property, this way:

self.headerView = NSBundle.mainBundle().loadNibNamed("HeaderView", owner: self, options: nil)[0] as? HeaderView

Upvotes: 1

Related Questions