從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拖到主項目中,添加引用即可加載。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM