0

I've created a view:

import UIKit

class TestNotWorkingView: UIView {
    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
}

And connected with the corresponding XIB: xib

Then, I've added the view to the UIViewController on the Storyboard:

view on storyboard

class ViewController: UIViewController {
@IBOutlet weak var testNotWorkingView: TestNotWorkingView!
override func viewDidLoad() {
    super.viewDidLoad()
    print(testNotWorkingView)
    print(testNotWorkingView.label1)
}

}

When I run the app, only the parent view appears. No labels are visible:

Parent view:

Optional(TestProject.TestNotWorkingView: 0x7fb165e04610; frame = (0 0; 414 818); autoresize = RM+BM; layer = CALayer: 0x600001f254e0)

Querying one of the labels

nil

I've already set the TestNotWorkingView as the view's class and file owner.

I assume since the views are not present on the storyboard, they're not being created and linked at runtime.

How can I use views created in XIBs inside a ViewController created in Storyboard? Is it possible at all?

Test Project that fully reproduces the issue

Richard Topchii
  • 7,075
  • 8
  • 48
  • 115

1 Answers1

0

Using view designed in xib can be a bit tricky, you need to add this code to your TestNotWorkingView class:

override func awakeAfter(using aDecoder: NSCoder) -> Any? {
    guard subviews.isEmpty else {
        return self
    }
    return Bundle.main.loadNibNamed("TestNotWorkingView", owner: nil, options: nil)?.first
}

EDIT: also, you should leave File's Owner Empty, and connect outlets only to TestNotWorkingView

pcz
  • 2,629
  • 2
  • 11
  • 15