Here is my Objective-C code which I'm using to load a nib for my customised UIView
:
-(id)init{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil];
return [subviewArray objectAtIndex:0];
}
What is the equivalent code in Swift?
Tested in Xcode 7 beta 4 , Swift 2.0 and iOS9 SDK . The following code will assign xib to the uiview. You can able to use this custom xib view in storyboard and access the IBOutlet object also.
Access customview programatically
Source code - https://github.com/karthikprabhuA/CustomXIBSwift
I achieved this with Swift by the following code:
Don't forget to connect your XIB view outlet to view outlet defined in swift. You can also set First Responder to your custom class name to start connecting any additional outlets.
Hope this helps!
The most convenient implementation. Here you need two methods, in order to return directly to the object of your class, not UIView.
Example:
Original Solution
.
Note that this way I get a class that loads itself from nib. I could then use SomeView as a class whenever UIView could be used in the project (in interface builder or programmatically).
Update - using Swift 3 syntax
Loading a xib in the following extension is written as an instance method, which can then be used by an initializer like the one above:
And the caller method might look like this:
Credit: Using a generic extension in this solution was inspired by Robert's answer below.
Edit Changing "view" to "contentView" to avoid confusion. Also changed the array subscript to ".first".
I just do this way :
This sample uses the first view in the nib "MyView.xib" in the main bundle. But you can vary either the index, the nib name, or the bundle ( main by default ).
I used to awake views into the view init method or make generic methods as in the solutions above ( which are smart by the way ) , but I don't do it anymore.
This way I can use different layouts or traits while keeping the same view logic and code.
I find easier to let a factory object ( usually the viewController that will use the view ) create it as it needs it. Sometimes you need an owner ( Usually when the created view got an outlet connected to the creator ) , sometimes not..
That's probably why Apple did not include an
initFromNib
method in its UIView class...To take a ground level example, you don't know how you are born. You just are born. So are the views ;)