Hugo Fouquet
Hugo Fouquet

Reputation: 149

Import Nib View in Storyboard ViewController

Swift 3 - Xcode 8 - iOS10

I have a xib file with a UIView. I want import this view in my ViewController.

My Player.xib

enter image description here

enter image description here

And my Storyboard result : enter image description here

And my Class:

@IBDesignable
class EmbedPlayerViewV2: UIView {

    @IBOutlet weak var subTitleLbl: UILabel!

    var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        loadViewFromNib()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        loadViewFromNib()
    }

    func loadViewFromNib() {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "Player", bundle: bundle)
        self.view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        self.addSubview(self.view)
    }

    override func layoutSubviews() {
        subTitleLbl.text = "LOADED"
        // ...
    }
    // ...
}

Upvotes: 0

Views: 612

Answers (1)

Hugo Fouquet
Hugo Fouquet

Reputation: 149

I have solved my problem.

func loadViewFromNib() {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "Player", bundle: bundle)
    self.view = nib.instantiate(withOwner: self, options: nil).first as! UIView
    self.addSubview(view)
    view.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
    view.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
    view.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    view.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}

Tanks Aaron

Upvotes: 1

Related Questions