Search code examples
iosswiftinitializationxibcustom-view

Swift assign text to label in xib file


I have a CustomView.swift (subclass of UIView) connected to CustomView.xib in my project.

(note: set the xib class to CustomView but did not set owner)

Load the xib file in CustomView.swift:

class CustomView: UIView {

    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }*/

    override init(frame: CGRect) {
        super.init(frame: frame)
        let subView: UIView = loadViewFromNib()
        subView.frame = self.bounds
        //label1.text = "123" //would cause error
        addSubview(subView)
    }

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

    func loadViewFromNib() -> UIView {
        let view: UIView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
        return view
    }
}

Somewhere I make the custom view:

let myCustomView:CustomView = CustomView.init(frame: CGRectMake(0, 0, 100, 100))
myCustomView.label1?.text = "123"
myCustomView.label2?.text = "abc"
print(myCustomView.label1.text)// returned nil

Nothing shows up on xib labels.

Should I write an extension for CustomView.swift and add a function assigning text?


Solution

  • You have to load from Nib

    //let myCustomView:CustomView = CustomView.init(frame: CGRectMake(0, 0, 100, 100))
    let myCustomView:CustomView = UINib(nibName: "CustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! CustomView
    
    myCustomView.label1?.text = "123"
    myCustomView.label2?.text = "abc"
    print(myCustomView.label1.text)