自定义xib 使用IBDesignable加载到storyboard 出现Failed to render and update auto layout status for controller (--**):The agent threw an exception。
1.自定义View的代码与关联如下:
@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 无法显示以及错误信息:
3.修复方法以及修复后添加IBInspectable 效果:
@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中看到该设置选项,如下图:
一点个人小分享,转载请注明出处!
贴个建站用vps推荐,有需要的可以点一下(⁎⁍̴̛ᴗ⁍̴̛⁎)