Addsubview自定义xib文件错误

时间:2016-11-10 12:29:18

标签: ios swift3

我正在使用Swift 3,我在将xib文件添加为子视图时出错

let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "CustomView", bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
    view.frame = bounds
    view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.addSubview(view);

enter image description here

有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

试试这个,它适用于swift 3.

let view =  Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as! UIView
  self .addSubview(view)

答案 1 :(得分:0)

在我的自定义视图类中,我实现如下:

import UIKit

@IBDesignable class TestView: UIView {

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

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func loadViewFromNib(){
        let view =  Bundle.main.loadNibNamed("test", owner: self, options: nil)?.first as! UIView
        print(view.backgroundColor ?? UIColor.blue)
    }
}

然后在我想要添加此自定义视图的ViewController中,我写如下:

let view = TestView()

我没有发现任何崩溃。