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?
Remember to name your Xib file exactly as your UIView subclass and set the type of the main view in that Xib file correctly. As soon as SE-0068 will be implemented one could drop the protocol and move the function directly into the UIView extension.
for Swift 4
extension UIView { class func loadFromNibNamed(nibNamed: String, bundle: Bundle? = nil) -> UIView? { return UINib( nibName: nibNamed, bundle: bundle ).instantiate(withOwner: nil, options: nil)[0] as? UIView } }
for Swift 3
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.
This worked for me.
override func awakeAfterUsingCoder(aDecoder: NSCoder) -> AnyObject? { if self.subviews.count == 0 { return loadNib() } return self } private func loadNib() -> YourCustomView { return NSBundle.mainBundle().loadNibNamed("YourCustomViewNibName", owner: nil, options: nil)[0] as YourCustomView }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With