以编程方式从MainViewController转换到Swift中的.xib视图?

时间:2015-10-24 15:50:43

标签: ios swift uiviewcontroller segue

我无法找到有关执行segue的帮助,或者至少在iOS 8或更高版本中使用swift进行某种视图转换。我试图尽量避免使用Storyboard编辑器,除了从主视图控制器到xib实现segue。

这是我到目前为止所做的:

    let bundle = NSBundle(forClass: self.dynamicType)
    let secondViewController = ViewController(nibName: "SwitchRegionSegue", bundle: nil)
    self.presentViewController(secondViewController, animated: true, completion: nil)

使用Single View Application新项目脚手架从主ViewController.swift调用上面的代码。但它会导致崩溃:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "SwitchRegionSegue" nib but the view outlet was not set.'

我也有这两个文件:

SwitchRegionSegue.xib

SwitchRegionSegue.swift

我已确保xib的文件所有者自定义类设置为SwitchRegionSegue : UIView

我的SwitchRegionSegue.swift只是一个空白画布,看起来像这样:

import UIKit

class SwitchRegionSegue: UIView {

    var view: UIView!

    var nibName = "SwitchRegionSegue"

    func xibSetup() {
        view = loadViewFromNib()

        // use bounds not frame or it'll be offset
        view.frame = bounds

        // Make the view stretch with containing view
        view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
        addSubview(view)
    }

    func loadViewFromNib() -> UIView {

        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

        return view
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        xibSetup()
    }

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

}

有人知道我在这里做得不对吗? (建议使用好的swift& xib教科书会很棒)

2 个答案:

答案 0 :(得分:0)

.xib 文件中,必须有两件事:

  • 文件所有者代理的类在Identity检查器中设置为视图控制器的类。

  • 文件所有者代理的view出口必须连接到笔尖中的视图对象。

你忘记了其中一个。

答案 1 :(得分:0)

我从你的代码中注意到的问题:

1)从 UIViewController 继承 SwitchRegionSegue ,而不是 UIView

2)设置你的xib的类

3)将笔尖中的视图对象连接到视图插座

然后在主ViewController中编写此代码:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    let secondViewController = SwitchRegionSegue(nibName: "SwitchRegionSegue", bundle: nil)
    self.presentViewController(secondViewController, animated: true, completion: nil)
}