19

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

错误:IB Designables:无法更新自动布局状态:代理引发“NSInternalInconsistencyException”异常:无法在包中加载 NIB:“NSBundle(已加载)”,名称为“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 中?

4

2 回答 2

42

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

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

加载 nib 时,您依赖于在运行时将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)

这将使 Interface Builder 从与自定义视图类相同的包中加载您的 nib。

This applies to anything that's loaded from a bundle by your custom view. For example, localised strings, images, etc. If you're using these in your view, make sure you use the same approach and explicitly pass in the bundle for the custom view class.

于 2016-02-29T12:58:04.053 回答
3

The same viewpoint with "Josh Heald", We can't pass nil for bundle. And this one for who in object - 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;
}
于 2017-05-16T00:02:32.333 回答