至少在iOS 8或更高版本上,我无法在执行搜索或快速进行某种视图转换方面找到帮助。除了实现从Main View Controller到xib的segue之外,我试图尽可能避免使用Storyboard编辑器。
这是我到目前为止所拥有的:
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教科书会很棒)
最佳答案
我从您注意到的问题代码:
1)从UIViewController而不是UIView继承SwitchRegionSegue
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)
}