user3785463
user3785463

Reputation: 119

How to load custom UIView from xib using Swift 2?

The task is to create custom UIView that loads UI from .xib file using Swift. How do I do that?

I tried to do that using the code:

import UIKit

@IBDesignable class CustomView: UIView {

var view: UIView!

@IBOutlet weak var label: UILabel!

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

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

func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]

    addSubview(view)
}

func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "CustomView", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

    return view
}

}

It runs, but crashes with EXC_BAD_ACCESS and shows me the message:

warning: could not load any Objective-C class information. This will significantly reduce the quality of type information available.

Actually, I need to translate code given here http://qnoid.com/2013/03/20/How-to-implement-a-reusable-UIView.html to Swift 2.0, but I have no idea how to do this.

Upvotes: 1

Views: 1683

Answers (2)

ilnar_al
ilnar_al

Reputation: 952

Is it correct, that your class is called CustomView and you're loading CustomView.xib where the class for the view in xib is CustomView?

If that is so you probably do not understand what you're doing

Upvotes: 0

ko100v.d
ko100v.d

Reputation: 1156

Try

let yourView = NSBundle.mainBundle().loadNibNamed("youViewNibName", owner: self, options: nil).first as! YourView

Do it in your ViewController class, then you can access the view in required init with coder, where you should call xibSetup().

Upvotes: 1

Related Questions