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?
Here's an extension that uses generics for loading a
UIView
from a nibI prefer this since it doesn't require any additional setup in the nib. It is based on general naming conventions, so if your class is
CustomView
, and it matches a nib named:CustomView
, you could just do this:If you need to be specific about the nib name for whatever reason, pass a string arg:
Known Issues
Using this with a private view class seems to cause issues. This appears to be a system wide issue.
A nice way to do this with Swift is to use an enum.
Then in your code you can simply use:
You can do this via storyboard, just add proper constraints for view. You can do this easily by subclassing any view from your own let's say
BaseView
:Objective-C
Swift 4
I provide 2 variants how to add constraints - common one and within visual format language - select any you want :)
Also, by default assumed that
xib
name has same name as implementation class name. If no - just changexibName
parameter.If you subclass your view from
BaseView
- you can easily put any view and specify class in IB.My contribution:
Swift 3 / Swift 4
Then call it like this:
..or even:
Here is a clean and declarative way of programmatically loading a view using a protocol and protocol extension (Swift 4.2):
And you can use this like so:
Some additional considerations:
Custom Class
set (and outlets/actions set from there), not the File Owner's.