Swift: Load UIView From Nib File

 ·  · 

Snippets of two ways to load UIView from nib file.

 

1. Using NSBundle

func loadMyViewFromXib() -> UIView {
    let xibObjs = NSBundle.mainBundle().loadNibNamed("MyViewXib", owner: self, options: nil)
    let myView = xibObjs.last as! UIView
    return myView
}

 

2. Using UINib

func loadMyViewFromXib() -> UIView {
    let nib = UINib(nibName: "MyViewXib", bundle: NSBundle.mainBundle())
    let xibObjs = nib.instantiateWithOwner(self, options: nil)
    let myView = xibObjs.last as! UIView
    return myView
}