How do I make a custom initializer for a UIViewController subclass in Swift?(如何在 Swift 中为 UIViewController 子类制作自定义初始化程序?)
问题描述
抱歉,如果之前有人问过这个问题,我已经搜索了很多,很多答案来自早期的 Swift 测试版,当时情况有所不同.我似乎找不到明确的答案.
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
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
这篇关于如何在 Swift 中为 UIViewController 子类制作自定义初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Swift 中为 UIViewController 子类制作自定义初始化程序?
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01