25

I am trying to create an UIViewController from a Nib file. On Google I found that I can only load an UIView from Nib.

But some suggests that I could create a Nib file (of UIView) whose File Owner is set to our ViewController.

That is what I did, I got no crashes, but the View is just not displayed.

EDIT: Tried to push the viewcontroller like this

self.navigationController!.pushViewController(CoolViewController(), animated: true );

But it still showing black screen when it is pushed

XCode 6.3 - Not using Storyboards

Nischal Hada
  • 3,230
  • 3
  • 27
  • 57
JayVDiyk
  • 4,277
  • 22
  • 70
  • 135
  • I'm able to load UIViewControllers from nibs. Could you post the source code that you use to attempt the load? I don't use storyboards either. – Mike Crawford May 19 '15 at 03:35
  • I have just tried to Create a UIViewControler and check the "Also Create Xib" checkbox. And push it using self.navigationController!.pushViewController(CoolViewController(), animated: true ); – JayVDiyk May 19 '15 at 03:47

2 Answers2

31

Try this, you can load a UIViewController with nibName:

Swift

self.navigationController!.pushViewController(CoolViewController(nibName: "CoolViewControllerNibName", bundle: nil), animated: true )

Objective-C

CoolViewController*coolViewCtrlObj=[[CoolViewController alloc] initWithNibName:@"CoolViewControllerNibName" bundle:nil];
[self.navigationController pushViewController:coolViewCtrlObj  animated:YES];
mokagio
  • 16,391
  • 3
  • 51
  • 58
Sudhin Davis
  • 2,010
  • 13
  • 18
21

You need to allocate your ViewController, then initialize it by telling the iOS the name of the nib.

I see you're using Swift; I'm afraid I don't know swift, only objective-c. But here is how it would be done in objective-c:

[self.navigationController pushViewController [[[CoolViewController alloc] initWithNibName: @"CoolDesign" bundle: nil] autorelease];

... where "CoolDesign" is the base name of your nib. That is, you create CoolDesign.xib in Interface Builder, Xcode compiles the XML - text - xib into CoolDesign.nib, then you tell initWithNibName to open just @"CoolDesign".

It's not enough just to tell Interface Builder that a design document is a UIViewController. While in principle the iOS could figure out what you mean, also in principle you could have multiple nibs for a single UIViewController subclass.

Nischal Hada
  • 3,230
  • 3
  • 27
  • 57
Mike Crawford
  • 2,232
  • 2
  • 18
  • 28
  • This is not preferred. The nib should load without referencing the name. –  Jan 26 '16 at 17:27
  • @benjaminhallock you can have call method to return the nib name generally we name the xib file with same name.`NSStringFromClass([self class])` – Max Apr 07 '17 at 07:13
  • @Max No, the nib is attached without reference. –  Apr 12 '17 at 23:21
  • 2
    @benjaminhallock can you show a tutorial that doesn't require referencing the name and instead use another way? I'm rather new with nibs. – CyberMew May 04 '17 at 03:19