UIViewController 子类所需的初始值设定项 [英] Required initializers for a subclass of UIViewController

查看:30
本文介绍了UIViewController 子类所需的初始值设定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试学习有关创建容器视图控制器的教程.它在Objective-C中.我想将其转换为 Swift.我在这里发现了一些相同的问题,但我并没有从中得到太多.

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.

这是代码.

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.

推荐答案

问题是:如果你声明任何存储属性没有初始值,你必须实现你自己的初始化器来初始化它们.请参阅本文档.

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

像这样:

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.

正确的解决方案取决于你在哪里初始化currentDetailViewController.

The correct solution depends on where you initialize currentDetailViewController.

如果你总是在 viewDidLoad 中初始化它,那么你可以将它声明为 隐式解包可选"

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()
}

否则,如果 currentDetailViewController 可以是 nil,则应将其声明为 可选"

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

var currentDetailViewController: UIViewController?

这篇关于UIViewController 子类所需的初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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