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?
Swift 4
Don't forget to write ".first as? CustomView".
If you want to use anywhere
The Best Solution is Robert Gummesson's answer.
Then call it like this:
try following code.
Edit:
If you want the Swift UIView subclass to be entirely self contained, and have the ability to be instantiated using init or init(frame:) without exposing the implementation detail of using a Nib, then you can use a protocol extension to achieve this. This solution avoids the nested UIView hierarchy as suggested by many of the other solutions.
Building on the above solutions.
This will work across all project bundles and no need for generics when calling fromNib().
Swift 2
Swift 3
Can be used like this:
Or like this:
If you have a lot of custom views in your project you can create class like
UIViewFromNib
Swift 2.3
Swift 3
And in every class just inherit from
UIViewFromNib
, also you can overridenibName
property if.xib
file has different name: