簡體   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