从bundle中加载xib

很多时候为了封装,需要把一个View单独的做成一个组件,比如做成静态库。如果这个view是自定义的,并且使用了xib,那么在主工程中怎么使用呢?在静态库中,添加bundle,编译的时候并不会把xib编程nib,所以在主工程中加载xib就会报错。

我们工程静态库中自定义了一个tableViewCell和collectionCell来展示相册和照片使用的

在主工程viewDidLoad方法中注册。

    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"do_Album" ofType:@"bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
        UINib *nib = [UINib nibWithNibName:cellID bundle:bundle];
        [_collectionView registerNib:nib forCellWithReuseIdentifier:cellID];
        nibsRegistered = YES;
    }

如果现在的主工程目录如下图

如果按照上述代码加载xib,就会得到下述错误。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </private/var/mobile/Containers/Bundle/Application/2A73657C-E556-4572-B218-3EEB930C615A/TZImagePickerController.app> (loaded)' with name 'doYZAssetCell''

出现上述错误的原因是你打包静态库时,xib不会被编译成nib,而如果你直接在主项目中使用xib,编译的时候就会把xib编程nib。所以需要我们手动把xib编程nib。

通过命令:ibtool --errors --warnings --output-format human-readable-text --compile /Users/yz/iOSwork/sourceTree/do-iOS/do_Album/doExtLib/AlbumController/doYZAssetCell.nib /Users/yz/iOSwork/sourceTree/do-iOS/do_Album/doExtLib/AlbumController/doYZAssetCell.xib

编译好nib之后,在bundle中把xib替换掉,然后把bundle拖到主项目中,添加引用即可加载。

上述是我的解决方法,如果你有好的解决方案,欢迎指正。

posted @ 2016-02-26 08:59  yzVictory  阅读(2449)  评论(0编辑  收藏  举报