Ios 在Swift中以编程方式从MainViewController切换到.xib视图?
在使用至少iOS 8或更高版本的swift执行segue或某种视图转换时,我很难找到帮助。除了实现从主视图控制器到xib的分段之外,我正在尽量避免使用故事板编辑器 这就是我到目前为止所做的:Ios 在Swift中以编程方式从MainViewController切换到.xib视图?,ios,swift,uiviewcontroller,segue,Ios,Swift,Uiviewcontroller,Segue,在使用至少iOS 8或更高版本的swift执行segue或某种视图转换时,我很难找到帮助。除了实现从主视图控制器到xib的分段之外,我正在尽量避免使用故事板编辑器 这就是我到目前为止所做的: let bundle = NSBundle(forClass: self.dynamicType) let secondViewController = ViewController(nibName: "SwitchRegionSegue", bundle: nil) self.pr
let bundle = NSBundle(forClass: self.dynamicType)
let secondViewController = ViewController(nibName: "SwitchRegionSegue", bundle: nil)
self.presentViewController(secondViewController, animated: true, completion: nil)
上面的代码是使用单视图应用程序new project scaffold从主ViewController.swift调用的。但它会导致崩溃:
***由于未捕获的异常“nSinternalinconsistenceexception”而终止应用程序,原因:'-[UIViewController\u LoadViewFromNibName:bundle:]加载了“SwitchRegionSegue”nib,但未设置视图出口。
我还有以下两个文件:
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教科书会很棒)在.xib文件中,有两件事必须是正确的:
- 文件的所有者代理的类在Identity inspector中设置为视图控制器的类
- 文件所有者代理的
出口必须连接到nib中的视图对象视图
您忘记了这两个问题中的一个。我从您的代码中注意到的问题: 1) 从UIViewController继承SwitchRegionSegue而不是UIView 2) 设置xib的类 3) 将nib中的视图对象连接到视图插座 然后在主ViewController中编写以下代码:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let secondViewController = SwitchRegionSegue(nibName: "SwitchRegionSegue", bundle: nil)
self.presentViewController(secondViewController, animated: true, completion: nil)
}
既然你要一本教科书:(目前的版本是Swift,但事实没有改变,所以这就可以了)我的文件所有者没有视图出口,我完全知道你在说什么:但是,我的文件所有者在“SwitchRegionSegue”中没有视图出口。如何向我的xib文件的所有者提供视图出口?我已经在SwitchRegionSegue.swift中声明了一个名为“view”的UIView属性。
视图
出口仅在您完成第一步后才会出现,为文件的所有者提供了适当的视图控制器类。