Salah Salah - 6 months ago 46
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]

enter image description here

Can someone help me please?


In my Custom View Class i implemented as follow:

import UIKit

@IBDesignable class TestView: UIView {

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

    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 ??

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

let view = TestView()

and i dont find any crash.