Search code examples
iosxcodexibnib

Xcode - How IBOutlets and Nib files work?


I'm for the first time using nib files. I mean xib and the corresponding swift class.

Here is my swift class:

import UIKit

@IBDesignable class LittleVideoView: UIView {

    var view: UIView!

    var nibName: String = "LittleVideoView"

    // MARK: Views
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var clicksLabel: UILabel!
    @IBOutlet weak var channelNameLabel: UILabel!
    @IBOutlet weak var thumbnailImageView: UIImageView!

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

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

    func setup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        addSubview(view)
    }

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

From the editor view I created some IBOutlets as you can see. Everything works properly.

There is just something I don't understand. I am programmatically loading the nib in this class, so why can I create IBOutlets while Xcode doesn't really knows that I will really load the correct nib file? Shortly, I don't understand how IBOutlets can work in this case. So, how will Xcode correclty link the loaded UIView in the setup() method with the IBOutlets ?


Solution

  • Nib files have a "File's Owner" type which the editor uses to list available outlets and actions. However when the nib is loaded at runtime that type is not enforced. Outlet's are connected using -setValue:forKey: under the assumption that the "Owner" passed to instantiateWithOwner is compatible with any outlet bindings defined in the nib.

    One xib File with Multiple "File's Owner"s

    If you have an IBOutlet, but not a property, is it retained or not?