-6

When you load a UIViewController Subclass programmatically, any nib associated with that ViewController will not be loaded if you named any of the files a different name than your subclass.

The only way to load the nib automatically, without passing a string name to the initializer, is to make sure your x.nib and class.swift has the same name as the SubClass.

Is there a way around this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

12

According to the documentation, you actually can load a nib based view controller without naming it exactly the same thing. Although matching names is the most common way to do this, there's a second case, which should work even with Swift.

From the documentation:

If you use a nib file to store your view controller's view, it is recommended that you specify that nib file explicitly when initializing your view controller.

However, if you do not specify a nib name, and do not override the loadView method in your custom subclass, the view controller searches for a nib file using other means. Specifically, it looks for a nib file with an appropriate name (without the .nib extension) and loads that nib file whenever its view is requested. Specifically, it looks (in order) for a nib file with one of the following names:

  1. If the view controller class name ends with the word ‘Controller’, as in MyViewController, it looks for a nib file whose name matches the class name without the word ‘Controller’, as in MyView.nib.

  2. It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.

Moshe
  • 57,511
  • 78
  • 272
  • 425
  • I can confirm this, you can name the class file whatever you like. As long as the class and Nib match these criteria. –  Jan 26 '16 at 21:50