将视图从XIB加载到ViewController和VIewCell

时间:2015-07-11 15:21:41

标签: ios swift xib nib

我有一个带有自定义类 ProfileHeaderView 的XIB。 我还有 ProfileViewController ProfileTableViewCell ,两者都带有 IBOutlet profileHeader

我想要的是将nib加载到 profileHeader 中。到目前为止,我通过加载NIB然后将其添加为 profileHeader 的子视图来实现,我认为这不是最佳解决方案,我必须手动设置帧。

let view = NSBundle.mainBundle().loadNibNamed("ProfileHeaderView", owner: self, options: nil).last as! ProfileHeaderView
view.setFrame(...)
self.profileHeaderView.addSubview(self.view)

实现目标的最佳途径是什么?

1 个答案:

答案 0 :(得分:3)

首先,创建自定义视图类

class CustomView: UIView {

    // MARK: Custom View Initilization
    var view: UIView!

    func xibSetup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
        addSubview(view)
        //// additional setup here
    }
    func loadViewFromNib() -> UIView {
        let bundle = NSBundle(forClass: self.dynamicType)
        // set nibName to be xib file's name
        let nib = UINib(nibName: "CustomView", bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
        return view
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        xibSetup()
    }

}

其次,在CustomView.xibFile's owner自定义类设置为CustomView

之后,你已经完成了。您可以以编程方式创建自定义视图。

let customView = CustomView(frame: frame)
self.view.addSubview(customView)

或者使用storyboard,将UIView拖到ViewController并将UIView的自定义类设置为CustomView