Siu Chung Chan Siu Chung Chan - 7 months ago 18
Swift Question

Assign xib to the UIView in Swift

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?

Answer

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:

ViewDetailItem.loadFromNibNamed("ViewBtnWishList")

And you will be able to reuse that method on any view.