渲染故事板时出现IBDesignable错误

时间:2018-01-04 10:39:25

标签: ios swift ibdesignable

我尝试按照以下12进行操作,但是当我尝试在故事板中渲染自定义视图时,我收到了错误消息。

  

无法呈现和更新View Controller的自动布局状态。代理人抛出异常。

这是我到目前为止所尝试的:

@IBDesignable final class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

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

    private func setup() {
        let customViewNib = loadFromNib()
        customViewNib.frame = bounds
        customViewNib.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(customViewNib)
    }

    func loadFromNib() -> UIView {
        let nib = UINib(nibName: "CustomView", bundle: Bundle.main)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        return view
    }
}

我已经设置了自定义视图的文件所有者。

我创建了一个新的空项目来解决这个问题:

https://github.com/ivangodfather/CustomView

https://ufile.io/imr9p

enter image description here

2 个答案:

答案 0 :(得分:1)

它似乎在捆绑中的问题。

let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)

有关获取错误日志的详细信息,您可以看到以下答案:https://stackoverflow.com/a/42678873/2000162

答案 1 :(得分:0)

请尝试此替换功能

func loadFromNib() -> UIView {
        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
        return view
//        let nib = UINib(nibName: "CustomView", bundle: Bundle.main)
//        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
//        return view
    }