swift - 通过重写 init 从故事板初始化视图控制器

2024-01-11

我在故事板中定义了一个 ViewController 实例。我可以通过以下方式初始化它

var myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("myViewControllerIdentifier") as! ViewController

有没有办法重写 ViewController 的 init 方法,以便我可以使用它来初始化它

var myViewController = ViewController()

我尝试覆盖 init

convenience init() {
    self = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SearchTableViewController") as! SearchTableViewController
}

但编译器不喜欢这样。有任何想法吗?


便利初始化器必须始终委托给同一类的指定初始化器,并且指定初始化器必须调用超类初始化器。

由于超类没有适当的初始化程序,因此类工厂方法可能会更好:

static func instantiate() -> SearchTableViewController
{
    return UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SearchTableViewController") as! SearchTableViewController
}

然后使用:

var myViewController = SearchTableViewController.instantiate()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

swift - 通过重写 init 从故事板初始化视图控制器 的相关文章

随机推荐