Required initializers for a subclass of UIViewController

柔情痞子 提交于 2019-11-30 03:00:23

问题


I've been attempting to follow a tutorial about creating a container view controller. It's in Objective-C. I want to convert it to Swift. I've found some of the same questions here, but I didn't get too much out of them.

Here's the code.

import UIKit

class ContainerViewController: UIViewController { // Class "ContainerViewController" has no initializers - That I know why.

    // 'required' initializer 'init(coder:)' must be provided by a subclass of UIViewController

    var currentDetailViewController: UIViewController

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

I've tried doing what both errors say, but still doesn't work.


回答1:


The problem is: If you declare any stored properties without initial value, you must implement your own initializer to initialize them. see this document.

Like this:

var currentDetailViewController: UIViewController

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    currentDetailViewController = UIViewController()
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

convenience override init() {
    self.init(nibName: nil, bundle: nil)
}

required init(coder aDecoder: NSCoder) {
    currentDetailViewController = UIViewController()
    super.init(coder:aDecoder)
}

But, I think this is not what you want.

The correct solution depends on where you initialize currentDetailViewController.

If you always initialize it within viewDidLoad, then you can declare it as an "Implicitly Unwrapped Optional"

var currentDetailViewController: UIViewController!

override viewDidLoad() {
    super.viewDidLoad()
    self.currentDetailViewController = DetailViewController()
}

otherwise, If currentDetailViewController can be nil, you should declare it as an "Optional"

var currentDetailViewController: UIViewController?


来源:https://stackoverflow.com/questions/26838909/required-initializers-for-a-subclass-of-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!