Ios – Black screen when creating UITabBarController from xib

iosswiftuitabbarcontrollerxib

I try to create UITabBarController from xib. So I setup tab items in xib, connect classes and xibs names for controllers like that. Open image in full resolution.

like that

Then I set TabBarController as root view controller.

root view controller

As result, I get a black screen with no tab items.

black screen

I can create UITabBarController programmatically, so the question is: how can I get what I create in xib?

Best Answer

There is a special way in which view controllers within nibs must be loaded, else the class is loaded without any of the backing UI.

Create the following method in TabBarController:

class func instantiateFromNib() -> TabBarController {
    let nib = UINib(nibName: "TabBarController", bundle: nil)
    let vc = nib.instantiate(withOwner: nil, options: nil).first as! TabBarController
    return vc
}

Now, in your AppDelegate, invoke it like so:

window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = TabBarController.instantiateFromNib()
window?.makeKeyAndVisible()

Give this a try.

Related Topic