iOS: 在初始化 UIViewController 时将参数传递给私有框架

iOS: Passing Parameters to private Framework while Initializing a UIViewController

我正在尝试创建一个可以在我的应用程序中使用的自定义框架。当我在应用程序中从我的框架实例化我的第一个 ViewController 时,我想传入两个参数。

import UIKit

public class NewVC: UIViewController {
    public var startColor: String?
    public var endColor: String?

    public required init(startColor: String, endColor: String) {
        self.startColor = startColor
        self.endColor = endColor
        super.init(nibName: "sb", bundle: nil)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
}

现在,我正在尝试在 AppDelegate:

中实例化 NewVC
import NewVCFramework
//...
let vc = NewVC(startColor:"00ff33a", endColor:"ff0c756")
let s = UIStoryboard(name: "sb", bundle: NSBundle(forClass: vc))
//I get an error on the line above that points at vc
self.window?.rootViewController = s.instantiateInitialViewController()

以下是我得到的错误:

Error:  Cannot convert value of type 'NewVC' to expected argument type 'AnyClass' (aka 'AnObject.Type')

您正在将 NewVC 实例传递给期望 class 的 UIStoryboard init 方法。请改用 NewVC.self

此外,如果您使用故事板,将调用 init?(coder aDecoder: NSCoder) 而不是您的自定义 init。您可以在创建视图控制器实例后提供 startColorendColor

下面的代码应该可以解决您的问题:

import NewVCFramework
//...
let s = UIStoryboard(name: "sb", bundle: NSBundle(forClass: NewVC.self))
let vc = s.instantiateInitialViewController() as !NewVC // Will call init?(coder aDecoder: NSCoder) for NewVC
vc.startColor = "00ff33a"
vc.endColor = "ff0c756"
self.window?.rootViewController = vc