[swift] Load a UIView from nib in Swift

I just do this way :

if let myView = UINib.init(nibName: "MyView", bundle: nil).instantiate(withOwner: self)[0] as? MyView {
    // Do something with myView
}

This sample uses the first view in the nib "MyView.xib" in the main bundle. But you can vary either the index, the nib name, or the bundle ( main by default ).

I used to awake views into the view init method or make generic methods as in the proposed answers above ( which are smart by the way ), but I don't do it anymore because I have noticed use cases are often different, and to cover all cases, generic methods become as complex as using the UINib.instantiate method.

I prefer to use a factory object, usually the ViewController that will use the view, or a dedicated factory object or view extension if the view needs to be used in multiple places.

In this example, a ViewController loads a view from nib. The nib file can be changed to use different layouts for the same view class. ( This not nice code, it just illustrates the idea )

class MyViewController {
    // Use "MyView-Compact" for compact version
    var myViewNibFileName = "MyView-Standard"

    lazy var myView: MyView = {
        // Be sure the Nib is correct, or it will crash
        // We don't want to continue with a wrong view anyway, so ! is ok
        UINib.init(nibName: myViewNibFileName, bundle: nil).instantiate(withOwner: self)[0] as! MyView
    }()
}

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to uiview

How can I mimic the bottom sheet from the Maps app? UIView touch event in controller Swift addsubview and remove it Swift UIView background color opacity How do I change UIView Size? How to add constraints programmatically using Swift Load a UIView from nib in Swift Remove all constraints affecting a UIView How do I write a custom init for a UIView subclass in Swift? How to use UIVisualEffectView to Blur Image?

Examples related to xib

Load a UIView from nib in Swift Correct way to load a Nib for a UIView subclass How can I load storyboard programmatically from class? Load view from an external xib file in storyboard How to load a xib file in a UIView How to Empty Caches and Clean All Targets Xcode 4 and later Loaded nib but the 'view' outlet was not set How do you load custom UITableViewCells from Xib files?