[英]Fatal error: use of unimplemented initializer in custom navigationcontroller
我正在創建一個自定義導航控制器。 我有這樣的事情:
public class CustomNavigationController: UINavigationController {
// MARK: - Life Cycle
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
delegate = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
}
我想測試一下,所以我創建了一個像這樣的 CustomNavigationController:
CustomNavigationController(rootViewController: ViewController())
當我運行應用程序時,我得到了這個:
fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class 'TestApp.CustomNavigationController'
我沒有看到問題,有人可以幫我嗎?
UINavigationController
的init(rootViewController:)
可能調用了self.init(nibName:bundle:)
,您尚未實現它,因此它會引發錯誤。
除了已經覆蓋的初始化程序之外,您還應該覆蓋init(nibName:bundle)
。 init(nibName:bundle:)
是一個指定的初始化器,而init(rootViewController:)
是一個方便的初始化器。
在使用自定義導航控制器時,我們需要使用NavigationController
override init
屬性作為-
class CustomNavigationController: UINavigationController {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
}
& 在Appdelegate
類中使用 -
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let vc = ViewController(nibName: "ViewController", bundle: nil)
let navi = CustomNavigationController(rootViewController: vc)
window?.backgroundColor = .white
window?.rootViewController = navi
window?.makeKeyAndVisible()
return true
}
}
根據 Apple 文檔 - 為了簡化指定初始化器和便利初始化器之間的關系,Swift 對初始化器之間的委托調用應用了以下三個規則:
規則 1 指定初始化程序必須從其直接超類調用指定初始化程序。
規則 2 便利構造器必須從同一個類中調用另一個構造器。
規則 3 便利構造器最終必須調用指定構造器。
記住這一點的簡單方法是:-
我在 iOS 12.4 上的用戶遇到了這個問題,所以為了在我的自定義初始化程序中做一個解決方法,我做了這樣的事情:
init(rootViewController: UIViewController, numberOfPages: Int) {
self.numberOfPages = numberOfPages
if #available(iOS 13.0, *) {
super.init(rootViewController: rootViewController)
} else {
super.init(nibName: nil, bundle: nil)
self.viewControllers = [rootViewController]
}
}
對於 13 以下的每個 iOS 版本,我基本上以不同的方式初始化我的類。這似乎是最短的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.