Salah Salah - 25 days ago 9
iOS Question

Addsubview custom xib file error

I'm using Swift 3, I have error adding xib file as subview

let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustomView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(view);


enter image description here

Can someone help me please?

Answer

In my Custom View Class i implemented as follow:

import UIKit

@IBDesignable class TestView: UIView {

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

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func loadViewFromNib(){
        let view =  Bundle.main.loadNibNamed("test", owner: self, options: nil)?.first as! UIView
        print(view.backgroundColor ?? UIColor.blue)
    }
}

then In my ViewController where i want add this custom view i write as below:

let view = TestView()

and i dont find any crash.