自定义xib IBDesignable 下storyboard无法渲染报错Failed to render and update auto layout status...

自定义xib 使用IBDesignable加载到storyboard 出现Failed to render and update auto layout status for controller (--**):The agent threw an exception。

1.自定义View的代码与关联如下:


code.gif
@IBDesignable class MyCustomView: UIView {

    @IBOutlet var view: UIView!
    @IBOutlet weak var testLabel: UILabel!
    @IBOutlet weak var testButtom: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        customSetup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customSetup()
    }
    func customSetup() {
        view = (Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)?.first as! UIView)
        view.frame = bounds
        view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        addSubview(view)
    }
}

2.加载到storyboard 无法显示以及错误信息:


errorInfo.png

3.修复方法以及修复后添加IBInspectable 效果:


fixPic.png
@IBDesignable class MyCustomView: UIView {

    @IBOutlet var view: UIView!
    @IBOutlet weak var testLabel: UILabel!
    @IBOutlet weak var testButtom: UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        customSetup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customSetup()
    }
    @IBInspectable var testText: String?
        {
        get
        {
            return testLabel.text
        }
        set (testText)
        {
            testLabel.text = testText
        }
    }
    @IBInspectable var cornerValue: CGFloat
        {
        get
        {
            return self.view.layer.cornerRadius
        }
        set (cornerValue)
        {
            self.view.layer.cornerRadius = cornerValue
        }
    }
    func customSetup() {
//      view = (Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)?.first as! UIView)
        view = loadViewFromNibAction()
        view.frame = bounds
        view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        addSubview(view)
    }
    func loadViewFromNibAction() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib.init(nibName: "MyCustomView", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        return view
    }
}

4.使用Bundle.main在IBDesignable情况下无法在编译时获取到该view,运行后可以正常查看所以导致storyboard中无法看到。调整了bundle、nib的获取方式即可正常显示并处理错误,此外代码中添加了swift的IBInspectable的实现示例。添加IBInspectable后可以在storyboard中看到该设置选项,如下图:


自定义xib IBDesignable 下storyboard无法渲染报错Failed to render and update auto layout status..._第1张图片
IBInspectable.png

一点个人小分享,转载请注明出处!

你可能感兴趣的:(自定义xib IBDesignable 下storyboard无法渲染报错Failed to render and update auto layout status...)