从swift中单独的nib文件加载UIViewController?

时间:2014-11-24 06:30:31

标签: ios objective-c iphone swift uiviewcontroller

我把一个ViewController带到了单独的nib文件中。我的初始根视图控制器在storyBoard中设置。现在的问题是当我推送到这个控制器时,没有调用View hireachy方法(ViewDidLoad,ViewWillApper等)..

代码(已加载视图但方法未调用)

var viewController = UIViewController(nibName: "OfferDetailViewController", bundle: nil) as OfferDetailViewController
 self.navigationController?.pushViewController(viewController, animated: true);

如果我使用故事板,它的工作正常也是如此。

    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var viewController = mainStoryboard.instantiateViewControllerWithIdentifier("offer") as OfferDetailViewController     
   self.navigationController?.pushViewController(viewController, animated: true);

问题:使用storyboard查看层次结构方法是否正在调用,但没有使用单独的nib文件?

3 个答案:

答案 0 :(得分:43)

var viewController = OfferDetailViewController(nibName: "OfferDetailViewController", bundle: nil)

答案 1 :(得分:13)

这是一个很好的通用方法......

extension UIViewController {
    class func loadFromNib<T: UIViewController>() -> T {
         return T(nibName: String(describing: self), bundle: nil)
    }
}

let vc : OfferDetailViewController = OfferDetailViewController.loadFromNib()

答案 2 :(得分:5)

具有类型转换的解决方案:

extension UIViewController {
    static func initFromNib() -> Self {
        func instanceFromNib<T: UIViewController>() -> T {
            return T(nibName: String(describing: self), bundle: nil)
        }
        return instanceFromNib()
    }
}

享受:

let testVC = TestVC.initFromNib()
testVC.someCustomParam = "someValue"