如何在 SWIFT 中以编程方式将我的自定义控制器变成根控制器? (无法加载 NIB)
Posted
技术标签:
【中文标题】如何在 SWIFT 中以编程方式将我的自定义控制器变成根控制器? (无法加载 NIB)【英文标题】:How to turn my custom controller into root controller programmatically in SWIFT? (Could not load NIB) 【发布时间】:2021-08-26 16:27:42 【问题描述】:我在没有 StoryBoard 的 ios 14 中动态创建了一个 XCode 项目。 HomeViewController 是我的自定义类。我收到此错误:
*** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无法在包中加载 NIB:'NSBundle with name 'HomeViewController'”
这是我的场景代理类:
class SceneDelegate: UIResponder, UIWindowSceneDelegate
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else return
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)
window?.makeKeyAndVisible()
【问题讨论】:
只需像HomeViewController()
一样初始化视图控制器就可以了
【参考方案1】:
不要像这样初始化你的视图控制器:
window?.rootViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)
像这样初始化它:
window?.rootViewController = HomeViewController()
这是因为当您指定 nibName
时,iOS 认为您正在尝试从 Storyboard 或其他地方进行初始化。
完成代码:
class SceneDelegate: UIResponder, UIWindowSceneDelegate
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else return
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = HomeViewController()
window?.makeKeyAndVisible()
【讨论】:
以上是关于如何在 SWIFT 中以编程方式将我的自定义控制器变成根控制器? (无法加载 NIB)的主要内容,如果未能解决你的问题,请参考以下文章
如何在标准 UITableViewCell 中以编程方式自动布局右侧的自定义 UIButton。
如何在 Swift 中以编程方式创建 SplitViewController?
当 iAd 横幅出现时,如何将视图的内容上移? (在 Swift 中以编程方式)