Load UIViewController from the separate nib file in swift?

后端 未结 3 789
悲哀的现实
悲哀的现实 2021-02-02 10:39

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 Vi

相关标签:
3条回答
  • 2021-02-02 11:04
    var viewController = OfferDetailViewController(nibName: "OfferDetailViewController", bundle: nil)
    
    0 讨论(0)
  • 2021-02-02 11:04

    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"
    
    0 讨论(0)
  • 2021-02-02 11:08

    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()
    
    0 讨论(0)
提交回复
热议问题