Swift UIViewController自定义init()-无法将错误分配给self [英] Swift UIViewController Custom init() - Error cannot assign to self

查看:254
本文介绍了Swift UIViewController自定义init()-无法将错误分配给self的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我曾经覆盖了UIViewControllerinit方法.我无法在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆