Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign xib to the UIView in Swift

Tags:

swift

xib

uiview

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?

like image 635
Siu Chung Chan Avatar asked Jun 23 '14 15:06

Siu Chung Chan


People also ask

How do I load a Xib file in Swift?

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.


2 Answers

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.

like image 66
drewag Avatar answered Oct 04 '22 03:10

drewag


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 } 
like image 23
Dave Avatar answered Oct 04 '22 05:10

Dave