Custom init of UIViewController from storyboard

后端 未结 3 1129
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 05:52

I tried finding some relevant questions but couldn\'t get anything, hope someone can help.

I set up some UIViewController\'s on a storyboard. I then want to load one

3条回答
  •  没有蜡笔的小新
    2020-12-29 06:01

    A simplification of my prior answer which is quick and avoids alternative hacky fixes:

    Here is a detail view controller you may want to instantiate from storyboard with an objectID set:

    import UIKit
    
    class DetailViewController: UIViewController {
    
        var objectID : Int!
    
        internal static func instantiate(with objectID: Int) -> DetailViewController {
    
            let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as DetailViewController
            vc.objectID = objectID
            return vc
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            if((objectID) != nil){
                print("Here is my objectID: \(objectID)")
            }
        }
    }
    

    Here is how you would use it to push onto a navigation controller with objectID set to 1:

    self.navigationController.pushViewController(DetailViewController.instantiate(1), animated: true)
    

    Added a blog post: https://theswiftcook.wordpress.com/2017/02/17/how-to-initialize-a-storyboard-viewcontroller-with-data-without-segues-swift-3-0git/

    Link to example on GitHub: https://github.com/hammadzz/Instantiate-ViewController-From-Storyboard-With-Data

提交回复
热议问题