【问题标题】:Could not load NIB from my own Pod无法从我自己的 Pod 加载 NIB
【发布时间】:2017-06-01 12:22:36
【问题描述】:

我的 Pod 框架中有一个 CalendarCell.xib 和一个 CalendarCell.swift UIView 子类。 CalendarCell.swift 有连接到它的视图的网点。在运行时我得到这个错误:

无法在包中加载 NIB:“NSBundle(已加载)”,名称为“CalendarCell”

在我的 podspec 文件中,我创建了一个捆绑资源:

s.resource_bundles = { 'Resources' => ['MyFramework/**/*.{xib,xcassets}'] }

如果我安装我的 Pod,我可以看到 xib 文件,但它崩溃了,现在看来 xib 文件和它的 swift 对应文件位于不同的包中。

任何帮助将不胜感激!

【问题讨论】:

    标签: ios frameworks cocoapods bundle xib


    【解决方案1】:

    没错,xib 存储在不同的包中。您需要找到 xibs 包的路径并从该包中加载所有 xib,而不是从主包中加载它们。

    要查找包的路径,在 Swift 3 中:

    let bundle = Bundle(for: YourClass.self)
    

    因此,您必须从该捆绑包中加载您的 UINib

    let nib = UINib(nibName: "YourXibName", bundle: bundle)
    

    并将其注册到您的UITableView/UICollectionView,如果您为此需要它:

    self.tableView.register(nib, forCellReuseIdentifier: "cellIdentifier")
    

    【讨论】:

    • 由于某种原因,我无法让您的解决方案发挥作用,但我找到了正确的方法。 let bundle = Bundle(for: CalendarCell.self) let nib = UINib(nibName: "CalendarCell", bundle: bundle) 谢谢你的帮助,拯救了我的一天 :)
    • 是的,可能存在一些差异,可能是您组织 Pods 项目或文件的方式。这个解决方案对我有用。无论如何,一般的方法是从不同的包中加载 xib。也谢谢你:)
    • bundle.loadNibNamed("YourClass", owner: nil, options: nil)!.first as! YourClass 为我工作。
    【解决方案2】:

    这是我在 swift 中使用的,它也适用于主包和框架

    extension UINib {
        func instantiate() -> Any? {
            return self.instantiate(withOwner: nil, options: nil).first
        }
    }
    extension UIView {
    
        static var nib: UINib {
            return UINib(nibName: String(describing: self), bundle: Bundle.init(for: self))
        }
    
        static func instantiate(autolayout: Bool = true) -> Self {
            // generic helper function
            func instantiateUsingNib<T: UIView>(autolayout: Bool) -> T {
                let view = self.nib.instantiate() as! T
                view.translatesAutoresizingMaskIntoConstraints = !autolayout
                view.autoresizingMask = []
                return view
            }
            return instantiateUsingNib(autolayout: autolayout)
        }
    }
    

    要初始化视图使用

    let myView = MyView.instantiate()
    

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2012-06-03
      • 2011-07-03
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多