繁体   English   中英

Swift UIViewController自定义init() - 错误无法分配给self

[英]Swift UIViewController Custom init() - Error cannot assign to self

在Objective-C中,我用来覆盖我的UIViewControllerinit方法。 我无法在Swift中实现同样的目标:

Objective-C代码:

- (instancetype)init
{
    self = [super init];
    if (self) {
        self = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"ViewController"];
    }
    return self;
}

如果我尝试在Swift中这样做,我会收到“无法分配给自己”的错误。 我已经实现了initWithCoder:方法,只是为了解决一些错误。

有人可以告诉我如何将上述Objective-C代码移植到Swift以获得所需的行为。

我想从storyboard初始化ViewController。

你不能在init分配self 您应该使用class方法或公共函数。

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中的init方法与objc中的方法不同。

在objc the only requirement for init method is that the initializing method begins with the letters “init” 您在此方法中创建一个实例并分配给指针self

而在swift中, Initializing is the process of preparing an instance of a class, structure, or enumeration for use 这有点像你已经有一个实例的self指向。 你在init方法中做的是设置self的属性和其他

这就是为什么你不能在课堂上快速分配给自己的原因

但你可以在struct的变异方法中赋予self

我建议你这样写

class func customInit -> XXXController {
    var vc: XXXController = XXXController()
    //  write something that you want to initialize 
    return vc 
}

就像你写objc一样

- (instancetype)initCustom {
    self = [super init];
    if (self) {
       //  write something that you want to initialize 
    }
    return self; 
}

你可以细胞

var customVc: XXXController = XXXController.customInit()

就像

XXXController *vc = [[XXXController alloc] initCustom]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM