ios 快速从单独的 nib 文件加载 UIViewController?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27099054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load UIViewController from the separate nib file in swift?
提问by Sunny Shah
I had take one ViewController with separate nib file. and my initial root viewcontroller is set in the storyBoard. Now the problem is that when I push to this controller the View hireachy methods are not being called (ViewDidLoad , ViewWillApper , etc)..
我拿了一个带有单独 nib 文件的 ViewController。我的初始根视图控制器设置在故事板中。现在的问题是,当我推送到这个控制器时,没有调用 Viewhireachy 方法(ViewDidLoad、ViewWillApper 等)。
Code(View is loaded but methods are not calling)
代码(视图已加载但方法未调用)
var viewController = UIViewController(nibName: "OfferDetailViewController", bundle: nil) as OfferDetailViewController
self.navigationController?.pushViewController(viewController, animated: true);
The same thing if i do with the storyboard its working fine.
同样的事情,如果我用故事板做它的工作正常。
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var viewController = mainStoryboard.instantiateViewControllerWithIdentifier("offer") as OfferDetailViewController
self.navigationController?.pushViewController(viewController, animated: true);
Problem: With storyboard View hierarchy methods are calling but not with the separate nib file?
问题:使用故事板视图层次结构方法调用但不使用单独的 nib 文件?
回答by aelam
var viewController = OfferDetailViewController(nibName: "OfferDetailViewController", bundle: nil)
回答by Ankit Srivastava
Here is a nice generic approach...
这是一个很好的通用方法......
extension UIViewController {
class func loadFromNib<T: UIViewController>() -> T {
return T(nibName: String(describing: self), bundle: nil)
}
}
let vc : OfferDetailViewController = OfferDetailViewController.loadFromNib()
回答by dr OX
solution with type casting:
类型转换的解决方案:
extension UIViewController {
static func initFromNib() -> Self {
func instanceFromNib<T: UIViewController>() -> T {
return T(nibName: String(describing: self), bundle: nil)
}
return instanceFromNib()
}
}
enjoyment:
享受:
let testVC = TestVC.initFromNib()
testVC.someCustomParam = "someValue"