Siempay
Siempay

Reputation: 1002

Loading iOS view dynamically from xib file

Ive been searching for a while for a simple example on how to reuse views from xib files in my storyboard but all i find was outdated or dosen't solve my problem the situation is that I has simple:

thank you

Upvotes: 0

Views: 2342

Answers (2)

Luca Davanzo
Luca Davanzo

Reputation: 21528

I've implemented an extension for UIView:

extension UIView {

    static func createInstance<T: UIView>(ofType type: T.Type) -> T {
        let className = NSStringFromClass(type).components(separatedBy: ".").last
        return Bundle.main.loadNibNamed(className!, owner: self, options: nil)![0] as! T
    }

}

In this way, wherever you can load your custom view in this way:

func override viewDidLoad() {
    super.viewDidLoad()
    let customView = UIView.createInstance(ofType: CustomView.self) 
    self.view.addSubview(customView)
}

Upvotes: 4

Phani Sai
Phani Sai

Reputation: 1233

Add bellow code in your custom view class

class MyCustomView: UIView {


   @IBOutlet var contentView: UIView! // take view outlet

    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }


    func xibSetup() {
        contentView = loadViewFromNib()

        // use bounds not frame or it'll be offset
        contentView!.frame = bounds

        //Make the view stretch with containing view
        contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]

        // Adding custom subview on top of our view (over any custom drawing > see note below)
        addSubview(contentView!)
        layoutIfNeeded()
    }

    override func layoutIfNeeded() {
        super.layoutIfNeeded()
        print("layoutIfNeeded")


    }

    func loadViewFromNib() -> UIView! {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        return view
    }
}

Add this class as superclass view in storyboard.

Upvotes: 1

Related Questions