Load a UIView from nib in Swift

My contribution:

extension UIView {
    class func fromNib<T: UIView>() -> T {
        return Bundle(for: T.self).loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
    }
}

Then call it like this:

let myCustomView: CustomView = UIView.fromNib()

..or even:

let myCustomView: CustomView = .fromNib()

Leave a Comment