ios - 无法加载 bundle 中的 NIB。 cocoa pod 项目

标签 ios swift cocoapods bundle xib

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

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
}

关于ios - 无法加载 bundle 中的 NIB。 cocoa pod 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546078/

相关文章:

ios - 如果用户取消登录,Swift ios facebook 登录会使应用程序崩溃

点击另一个 TextField 时,SwiftUI TextField 不会提交更改

swift - 在应用目标和测试目标中实现的类

javascript - 如何将 React Native 与 Dreamfactory REST API 集成?

iphone - 在 UIWebview 中重新加载 gif 图像

swift - 未找到框架 FBLPromises(Swift 包管理器)

ios - 在遗留代码中使用 Firebase 数据库与 Google Cloud Messaging

ios - Swift 项目中的 Cocoa pods objective c 文件。桥接问题

ios - 使用 count() 时 swift 出现奇怪的错误

ios - 从上下文创建子图像