如何在 Swift 中编写 UIViewController 的 init 方法 [英] How to write init methods of a UIViewController in Swift

查看:43
本文介绍了如何在 Swift 中编写 UIViewController 的 init 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法向以下 UIViewController 类添加 init 方法.我需要在 init 方法中编写一些代码.我必须编写 init(coder) 方法吗?即使我添加了编码器和解码器方法,我仍然会出错.我也尝试使用不带任何参数的 init 方法,但这似乎也不起作用.

I am unable to add init method to the following UIViewController class. I need to write some code in the init method. Do i have to write init(coder) method? Even when I add the coder and decoder methods I still get errors. I also tried using the init method without any parameters but that also does not seem to work.

class ViewController: UIViewController {

    var tap: UITapGestureRecognizer?

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)   {
        super.init(nibName: nil, bundle: nil)
        tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    }

...
...
}

如果我不带参数调用 super.init() 方法,则错误是必须调用超类的指定初始化程序",如果我传递参数 nib 和 bundle,则错误是必需的初始化程序 init(coder)".

If I call the super.init() method without parameters the error is "Must call a designated initializer of super class" and if I pass the parameter nib and bundle then error is "Required initializer init(coder)".

即使我添加了 init(coder) 和 init(decoder) 它也不起作用.

Even when I add init(coder) and init(decoder) it does not work.

推荐答案

我用过:

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

有人建议:

convenience init(){
    self.init()
}

但这会给你一个无限循环.

But this gives you an infinite loop.

这篇关于如何在 Swift 中编写 UIViewController 的 init 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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