无法加载捆绑包中的 NIB。 Cocoa Pod 项目

Could not load NIB in bundle. Cocoa Pod project

我正在做一个简单的 cocoa pod,它是一个自定义的 UICollectionView。但是我无法使用 UICollectionViewCell 的 xib 文件。我收到错误:由于未捕获的异常 'NSInternalInconsistencyException' 而终止应用程序,原因:'无法在捆绑包中加载 NIB:'NSBundle (loaded)' 名称 'CWNumberedCollectionViewCell'。

import UIKit
class CWNumberedCollectionViewCell: UICollectionViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
}


import Foundation
import UIKit

public class CWCollectionViewNumbered: UICollectionView{

    let cellIdentifier = "CWCell"

    public init(frame: CGRect, layout: UICollectionViewFlowLayout, parent: UIView) {
        super.init(frame: frame, collectionViewLayout: layout)
        self.allowsMultipleSelection = true
        self.delegate = self
        self.dataSource = self
        self.register( UINib.init( nibName:"CWNumberedCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
        self.backgroundColor = UIColor.blue
    }

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

    override public func selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) {
        print("tapped")
    }
}

I have added the xib file to copy bundle resource.

xib 不在您要查找的模块中。您必须精确定位 xib 所在的当前模块包,例如使用 let bundle = Bundle(for: self)。否则链接器将在主包中寻找资源。

这是我如何从 xib 文件加载图像的示例:

class func loadImage(imageSize: ImageSize) throws -> UIImage {
    let bundle = Bundle(for: self)
    let imageName = self.imageName(imageSize)
    guard let image = UIImage(named: imageName, in: bundle, compatibleWith: .none) else {
        throw LoadingIndicatorError.missingImage
    }
    return image
}