in objective c it can be done in init method by
-(id)init{
self = [[[NSBundle mainBundle] loadNibNamed:@"ViewBtnWishList" owner:0 options:nil] objectAtIndex:0];
return self;
}
but when i do this in swift
init(frame: CGRect) {
self = NSBundle.mainBundle().loadNibNamed("ViewDetailMenu", owner: 0, options: nil)[0] as? UIView
}
cannot assign to self in a method error is shown. now my approach is to create a view, and add the view loaded from nib to it. anyone have a better idea?
that may be a solution for you:
Swift 3.x
Swift 2.x
This worked for me.
Just made a
UINib
extension to load a view from xib and embed into a container view using constraints, using generics and strong naming (without using Strings, assuming you have the same file name for xib and implementation):Usage:
for Swift 4
for Swift 3
You could create an extension on UIView:
Note: Using UINib is faster because it does caching for you.
Then you can just do:
And you will be able to reuse that method on any view.
instead of adding an extension to UIView, you could define a protocol and add the implementation to a protocol extension. You can then declare that UIView conforms to the protocol.
This allows the return type to be
Self
instead ofUIView
. So the caller doesn't have to cast to the class.Explained here: https://stackoverflow.com/a/33424509/845027
Tested in Xcode 7 beta 4 , Swift 2.0 . The following code will assign xib to the
UIView
. You can use this custom xib view in storyboard and access theIBOutlet
object also.Access customview programatically
Source code - https://github.com/karthikprabhuA/CustomXIBSwift