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?
Similar to some of the answers above but a more consistent Swift3 UIView extension:
Which gives the convenience of being able to load the class from a self named nib but also from other nibs/bundles.
More powerful version based on Logan's answer
And you can use like
I prefer this solution (based on the answer if @GK100):
In SomeView.swift, I loaded the XIB inside the
init
orinit:frame: CGRect
initializer. There is no need to assign anything to "self". As soon as the XIB is loaded, all outlets are connected, including the top level view. The only thing missing, is to add the top view to the view hierarchy:All you have to do is call init method in your
UIView
class.Do it that way:
Now, if you want to add this view as a sub view in view controller, do it that way in view controller.swift file:
Swift 3 version of Logan's answer
Swift 4 Protocol Extensions
Adoption
This implementation assumes that the Nib has the same name as the UIView class. Ex. MyView.xib. You can modify this behavior by implementing nibName() in MyView to return a different name than the default protocol extension implementation.
In the xib the files owner is MyView and the root view class is MyView.
Usage