How to instantiate a view controller programatically, without storyboard

↘锁芯ラ 提交于 2019-12-12 02:44:38

问题


Is there a way to instantiate a view controller programatically without using storyboard identifier. I want to push CNContactPickerController into my root view controller .

let controller = CNContactPickerViewController()
controller.delegate = self
navigationController?.present(controller, animated: true, completion: nil)

i did this but in contactPicker (delegate) i push a VC from storyboard where i save what info i want from that specific contact. The problem: when i pop the last view controller i want to go on the CNConctactPickerControllerView but i go on the first view controller i tried with dismiss but nothing happens..


回答1:


The problem with doing this is that NONE of the UI for your view controller is created. What you are doing is simply instantiating an instance of the class. None of the corresponding UI is created, also your IBOutlets will be nil.

You have 2 options, either you use Interface builder and instantiate from the Nib or Storyboard, or you create ALL your UI manually in code.

For the sake of resuability you could create a static method on CNContactPickerViewController to handle the storyboard instantiation for you. See the following:

class CBContactPickerViewController: UIViewController {

    static func fromStoryboard() -> CNContactPickerViewController {
        return UIStoryboard(name: "foobar", bundle: nil).instantiateViewController(identifier: "CNContactPickerViewController") as! CNContactPickerViewController
    }
}

You can then utilise this as follows:

self.present(viewController: CNContactPickerViewController.fromStoryboard(), animated: true, completion: nil)


来源:https://stackoverflow.com/questions/40607951/how-to-instantiate-a-view-controller-programatically-without-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!