Siu Chung Chan Siu Chung Chan - 10 months ago 50
Swift Question

Assign xib to the UIView in Swift

in objective c it can be done in init method by

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?


You could create an extension on UIView:

extension UIView {
    class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> UIView? {
        return UINib(
            nibName: nibNamed,
            bundle: bundle
        ).instantiateWithOwner(nil, options: nil)[0] as? 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.