首页 > 解决方案 > XIB 无法从主包中加载。.... 为什么?

问题描述

场景:我正在尝试使用故事板的子视图引用 XIB 的“动态视图”。

但是我在加载位于主(当前)包中的特定 xib 文件时遇到问题。我认为这将是困难的。

以下是我的简单代码:

import UIKit

@IBDesignable
class AccountInformationView: UIView, Nib {
    let nibName = "AccountInformationView"
    var contentView: UIView?

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

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

    func commonInit() {
        guard let view = loadViewFromNib() else { return }
        view.frame = bounds
        addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
       // let bundle = Bundle(for: type(of: self))
        let mainBundle = Bundle.main
        let nib = UINib(nibName: nibName, bundle: mainBundle)
        // check the following line due to crash:
        _ = nib.instantiate(withOwner: self, options: nil).first as? AccountInformationView
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

它在该行崩溃:

nib.instantiate(withOwner: self, options: nil).first as? AccountInformationView

...原因:'无法在包中加载 NIB:'NSBundle(已加载)',名称为'AccountInformationView''

这是项目布局:
在此处输入图像描述

为什么我找不到 XIB?

标签: swiftxcodebundle

解决方案


我看到您的项目中有一个名为 AccountInformationView的xib 。但这并不意味着您的bundle中有相应的nib

  • 首先,xib可能不在应用程序目标中,因此相应的nib永远不会进入构建的应用程序包。

  • 其次,您没有提供足够的信息,但我猜测这段代码可能正在情节提要中运行(因为这是一个 IBDesignable 视图)——永远不会起作用,因为当时没有捆绑包,甚至如果有的话,xib还没有变成nib。只有建筑才能制造笔尖


推荐阅读