iOS Swift 子类化 ViewController 由 xib (nib) 文件初始化 [英] iOS Swift subclassing ViewController initialized by xib (nib) file

查看:30
本文介绍了iOS Swift 子类化 ViewController 由 xib (nib) 文件初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类

MyViewController: UIViewController

由 MyViewController.xib 初始化并带有一些插座.我只将 MyViewController.xib 中的 File Owner 类设置为 MyViewController,MyViewController.swift 中没有任何 init 方法(都继承自 UIViewController),以下行按预期工作:

let vc = MyViewController()

视图属性已设置,出口已设置.

我希望子类化 MyViewController:

SecondViewController: MyViewController{覆盖 init(){超级初始化()}需要初始化?(编码器aDecoder:NSCoder){super.init(编码器:aDecoder)}}

现在我期待那条线

let vc = SecondViewController()

将创建带有从 MyViewController 继承的视图和出口的视图控制器,但 vc 中的所有出口都为零.看起来 MyViewController.xib 文件现在丢失了.我做错了什么?

解决方案

您不能扩展 xib 文件.SecondViewController 应该有自己的 xib 文件和自己的出口.您可以在基类 MyViewController 中定义公共 UI 组件,并且对于您创建的每个 xib,将 ui 组件直接链接到基类.例如,如果您在所有视图控制器中有一个通用的自定义后退按钮,请在基类中添加插座定义,并为每个 xib 文件添加 UIButton 并将其插座设置为基类.

I have one base class

MyViewController: UIViewController

initialized by MyViewController.xib with some outlets. I only have set File Owner class in MyViewController.xib to MyViewController, no any init methods in MyViewController.swift (all inherited from UIViewController), and following line works just as expected:

let vc = MyViewController()

view property is set, outlets is set.

I wish to subclass MyViewController:

SecondViewController: MyViewController
{
    override init()
    {
        super.init()
    }

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

Now I expect that line

let vc = SecondViewController()

will create view controller with view and outlets inherited from MyViewController, but all outlets in vc are nil. Looks like MyViewController.xib file is now missed. What am I doing wrong?

解决方案

You can't extend the xib file. The SecondViewControllershould have its own xib file and its own outlets. You may define the common UI components in the base class MyViewController and for each xib you create, link the ui components directly to the base class. For example, if you have a common custom back button in all view controller, add the outlet definition in the base class and for each xib file add the UIButton and set its outlet to the base class.

这篇关于iOS Swift 子类化 ViewController 由 xib (nib) 文件初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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