无法渲染ClassName的实例:代理投掷异常加载包中的nib

无法渲染ClassName的实例:代理投掷异常加载包中的nib

问题描述:

当我将自定义IBDesignable视图包含在故事板或另一个nib中时,代理崩溃并抛出异常,因为它无法加载nib。无法渲染ClassName的实例:代理投掷异常加载包中的nib

error: IB Designables: Failed to update auto layout status: The agent raised a "NSInternalInconsistencyException" exception: Could not load NIB in bundle: 'NSBundle (loaded)' with name 'StripyView'

这是我用来加载笔尖代码:

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

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

func loadContentViewFromNib() { 
    let nib = UINib(nibName: String(StripyView), bundle: nil) 
    let views = nib.instantiateWithOwner(self, options: nil) 
    if let view = views.last as? UIView { 
     view.frame = bounds 
     view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] 
     addSubview(view) 
    } 
} 

从笔尖正确的,当我在模拟器中运行,为什么不会它在Interface Builder显示器中的视图的负荷?

当Interface Builder呈现您的IBDesignable视图时,它使用助手应用程序来加载所有内容。这样做的结果是mainBundle在设计时与辅助程序相关,它不是你的应用程序的mainBundle。你可以看到,在错误中提到的路径无关,与你的应用程序:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Overlays

当加载笔尖,你依靠的事实,传递bundle: nil默认为您的应用程序的mainBundle在运行时。

let nib = UINib(nibName: String(describing: StripyView.self), bundle: nil) 

因此,您需要在此处传递正确的包。修复以下行:

let bundle = Bundle(for: StripyView.self) 
let nib = UINib(nibName: String(describing: StripyView.self), bundle: bundle) 

这将使界面生成器从您的自定义视图类相同的包加载您的笔尖。

这适用于通过自定义视图从包中加载的任何内容。例如,本地化的字符串,图像等。如果您在视图中使用这些字符串,请确保您使用相同的方法并显式传递自定义视图类的包。

+4

谢谢!这从一些令人惊讶的教程中缺少。 – GoldenJoe

+2

如果我能,我会给你100分以上。我已经失去了很多时间。 –

+0

很高兴能帮到你,劳拉和乔! –

与“Josh Heald”相同的观点,我们不能通过捆绑零。和 这一个为谁在对象 - C:

- (UIView *) loadViewFromNib{ 
NSBundle *bundle = [NSBundle bundleForClass:[self class]]; 
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:bundle]; 
UIView *v = [[nib instantiateWithOwner:self options:nil]objectAtIndex:0]; 
return v; 
} 
+0

这是大约1岁,这不是我的完整解决方案,但这让我超过了主要障碍,让笔尖加载。谢谢!!! – Armand