Reputation: 593
I created new file and check Cocoa Touch Class
-> Then I set subclass as UIViewController
-> I mark "Also create XIB file".
It created simple UIViewController
as expected, but here is my question becuase when I called:
present(MyViewController(), animated: true)
This shows MyViewController()
as I wanted but how is it possible that I'm using simple init()
and Nib is loaded?
I thought that I need to use different initalizer, how Swift is doing this?
Upvotes: 0
Views: 61
Reputation: 318774
It's not "Swift" doing this. It's the implementation of the UIViewController
class. The same happens with Objective-C.
Start by reading the documentation for the UIViewController init(nibName:bundle:)
method and the nibName
property.
From the nibName
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:
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.
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.
Basically, in your case you use the default initializer meaning you specified nil
for the nib name. So at runtime, the nib you created with the same name as the view controller class is automatically found and used.
Upvotes: 3