Swift UIViewController自定义init()-无法将错误分配给self [英] Swift UIViewController Custom init() - Error cannot assign to self
问题描述
在Objective-C中,我曾经覆盖了UIViewController
的init
方法.我无法在Swift中实现相同的目标:
In Objective-C I used to override the init
method of my UIViewController
. I cannot achieve the same in Swift :
Objective-C代码:
Objective-C code :
- (instancetype)init
{
self = [super init];
if (self) {
self = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"ViewController"];
}
return self;
}
如果我尝试在Swift中这样做,则会收到无法分配给自己"的错误消息.我已经实现了initWithCoder:
方法只是为了解决更多错误.
If I try to do so in Swift I get errors for "Cannot assign to self". I have already implemented the initWithCoder:
method just to get through a few more errors.
有人可以告诉我如何将上面的Objective-C代码移植到Swift以获得所需的行为.
Can someone please tell me how can I port the above Objective-C code to Swift to get the desired behavior.
我想从情节提要中初始化ViewController.
I want to init the ViewController from storyboard.
推荐答案
您不能在init
中分配self
.您应该改用class
方法或公共函数.
You cannot assign self
in init
. You should use class
method or public function instead.
class func viewControllerFromStoryboard() -> ViewController? {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: ViewController.self))
if let controller = storyboard.instantiateViewControllerWithIdentifier("ViewController") as? ViewController
{
return controller
}
return nil
}
可以致电
let controller = ViewController.viewControllerFromStoryboard()
这篇关于Swift UIViewController自定义init()-无法将错误分配给self的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!