自定义静态Framework无法加载xib/nib文件导致崩溃问题求助
问题根因
你使用的Framework的Mach-O类型为静态库,静态库不存在独立的Bundle实体,所有静态库内的资源默认会被合并到宿主App的主Bundle中,原有两种获取Bundle的方式均无法正确匹配到资源存放路径,且Xcode 13的默认编译配置可能会导致资源未被正确打包到最终产物中。
解决方案
方案1:直接从主Bundle加载(快速修复,适合无重名资源的场景)
- 打开Framework项目的Target设置,进入「Build Phases」->「Copy Bundle Resources」,确认
MyNib.xib已经被添加到列表中 - 打开宿主App的Target设置,进入「Build Phases」->「Copy Bundle Resources」,手动添加
MyNib.xib到列表 - 修改获取Bundle的代码:
let bundle = Bundle.main let nib = UINib(nibName: "\(MyNib.self)", bundle: bundle) let array = nib.instantiate(withOwner: self, options: nil)
方案2:独立资源Bundle管理(推荐,适合多资源、对外发布的Framework)
- 在Framework项目中新建Target,类型选择「Bundle」,命名为
NibFrameworkResources - 将Framework所有的xib、图片等资源全部添加到该资源Bundle的「Copy Bundle Resources」列表中
- 将资源Bundle的Target添加到Framework的依赖中,确保编译Framework时会同步编译资源Bundle
- 修改Framework中获取资源Bundle的代码:
let frameworkBundle = Bundle(for: MyNib.self) guard let resBundlePath = frameworkBundle.path(forResource: "NibFrameworkResources", ofType: "bundle"), let resBundle = Bundle(path: resBundlePath) else { fatalError("资源包加载失败,请检查配置") } let nib = UINib(nibName: "\(MyNib.self)", bundle: resBundle) let array = nib.instantiate(withOwner: self, options: nil)
额外校验项
- 清理Xcode的DerivedData文件夹后重新编译全量项目
- 检查Framework和宿主App的「Build Settings」->「Build Active Architecture Only」配置,Debug模式下可临时改为No,避免架构适配导致的资源丢失
- 编译后打开App的ipa包,确认
MyNib.nib文件存在于包根目录或对应资源Bundle目录下
内容的提问来源于stack exchange,提问作者Rishab
相关产品推荐
相关产品推荐

