Xcode - IBOutlets和Nib文件如何工作?

时间:2016-11-12 00:06:30

标签: ios xcode xib nib

我是第一次使用nib文件。我的意思是xib和相应的swift类。

这是我的快速课程:

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

从编辑器视图中我可以看到一些IBOutlets。一切正常。

有一些我不明白的东西。我在这个类中以编程方式加载nib,为什么我可以创建IBOutlets,而Xcode并不真正知道我会真正加载正确的nib文件?不久,我不明白IBOutlets在这种情况下如何工作。那么,Xcode如何将setup()方法中加载的UIView与IBOutlets链接起来?

1 个答案:

答案 0 :(得分:2)

Nib文件有一个"文件的所有者"编辑器用于列出可用出口和操作的类型。但是,在运行时加载nib时,该类型不会强制执行。在假设"所有者"的情况下,使用-setValue:forKey:连接插座。传递给instantiateWithOwner与nib中定义的任何出口绑定兼容。

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

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

相关问题