Search code examples
iosswiftcocoapodsbundlexib

Could not load NIB in bundle. Cocoa Pod project


I am doing a simple cocoa pod that is a custom UICollectionView. But I am unable to use the xib file of UICollectionViewCell. I am getting the error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name '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.


Solution

  • The xib is not in the module you are looking for. You must precise the current module bundle the xib is located e.g. use let bundle = Bundle(for: self). Otherwise linker will look for resources in main bundle.

    Here's an example how I load image from xib file:

    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
    }