iOS调用framework中带XIB的ViewController报'Could not load NIB in bundle'崩溃
问题解决方案
崩溃根因
你初始化LoginViewController时传入的bundle参数为nil,此时系统会默认从App主Bundle中查找指定的XIB文件,但你的LoginViewController.xib是存放在LoginFrameWork.framework的资源包中,主Bundle不存在该文件,因此触发找不到NIB的崩溃。
修复步骤
- 第一步:确认XIB已加入Framework的资源构建项
打开LoginFrameWork项目的构建目标,进入Build Phases→Copy Bundle Resources,确保LoginViewController.xib在该列表中,若不存在手动拖拽添加。 - 第二步:修正XIB的File's Owner配置
选中LoginViewController.xib,打开右侧Identity检查器,确认File's Owner的Class设置为LoginViewController,且Module选择为LoginFrameWork,不要留空或者选择主App的模块。 - 第三步:修改初始化代码,指定正确的Bundle
修改MyApp中跳转逻辑的代码,明确指定Bundle为LoginFramework自身的Bundle:
@IBAction func launchLogin(_ sender: Any) { // 获取Framework对应的Bundle let frameworkBundle = Bundle(for: LoginViewController.self) // 传入正确的Bundle初始化控制器 let loginVC = LoginViewController(nibName: "LoginViewController", bundle: frameworkBundle) self.present(loginVC, animated: true) }
- 优化建议(可选)
可以直接在LoginViewController中封装好初始化方法,外部调用无需关心Bundle逻辑,降低使用成本:
在LoginFrameWork的LoginViewController中添加公开的初始化方法:
public class LoginViewController: UIViewController { // 原有代码保持不变 // 新增公开初始化方法 public static func instantiate() -> LoginViewController { let bundle = Bundle(for: LoginViewController.self) return LoginViewController(nibName: "LoginViewController", bundle: bundle) } }
外部调用直接写:
let loginVC = LoginViewController.instantiate()
内容的提问来源于stack exchange,提问作者CoolDocMan
相关产品推荐
相关产品推荐

