如何在Swift中为UIViewController子类创建自定义初始化程序? [英] How do I make a custom initializer for a UIViewController subclass in Swift?

查看:248
本文介绍了如何在Swift中为UIViewController子类创建自定义初始化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果以前已经问过这个问题,我已经搜索了很多内容,并且当情况有所不同时,许多答案来自早期的Swift beta.我似乎找不到确切的答案.

Apologies if this has been asked before, I've searched around a lot and many answers are from earlier Swift betas when things were different. I can't seem to find a definitive answer.

我想继承UIViewController的类,并具有一个自定义的初始化程序,使我可以轻松地在代码中进行设置.我在Swift中无法执行此操作.

I want to subclass UIViewController and have a custom initializer to allow me to set it up in code easily. I'm having trouble doing this in Swift.

我想要一个init()函数,我可以使用该函数传递特定的NSURL,然后将其与视图控制器一起使用.在我看来,它看起来像init(withImageURL: NSURL).如果我添加了该功能,它将要求我添加init(coder: NSCoder)功能.

I want an init() function that I can use to pass a specific NSURL I'll then use with the view controller. In my mind it looks something like init(withImageURL: NSURL). If I add that function it then asks me to add the init(coder: NSCoder) function.

我相信这是因为它在超类中用required关键字标记了吗?所以我必须在子类中这样做吗?我添加了它:

I believe this is because it's marked in the superclass with the required keyword? So I have to do it in the subclass? I add it:

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

现在呢?我的特殊初始化程序是否被视为convenience?指定一个?我叫超级初始化器吗?来自同一类的初始值设定项?

Now what? Is my special initializer considered a convenience one? A designated one? Do I call a super initializer? An initializer from the same class?

如何将特殊的初始化程序添加到UIViewController子类上?

How do I add my special initializer onto a UIViewController subclass?

推荐答案

class ViewController: UIViewController {

    var imageURL: NSURL?

    // this is a convenient way to create this view controller without a imageURL
    convenience init() {
        self.init(imageURL: nil)
    }

    init(imageURL: NSURL?) {
        self.imageURL = imageURL
        super.init(nibName: nil, bundle: nil)
    }

    // if this view controller is loaded from a storyboard, imageURL will be nil

    /* Xcode 6
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    */

    // Xcode 7 & 8
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

这篇关于如何在Swift中为UIViewController子类创建自定义初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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