Is it possible to check whether an identifier exists in a storyboard before instantiating the object?

后端 未结 6 1367
-上瘾入骨i
-上瘾入骨i 2021-02-19 06:53

In my code I have this line, but I was wondering if there is way to check whether @\"SomeController\" exists before I use it with the \"instantiateViewControllerWit

6条回答
  •  梦如初夏
    2021-02-19 07:11

    Swift 4.2.

    Declare an extension below.

    extension UIStoryboard {
        func instantiateVC(withIdentifier identifier: String) -> UIViewController? {
            // "identifierToNibNameMap" – dont change it. It is a key for searching IDs 
            if let identifiersList = self.value(forKey: "identifierToNibNameMap") as? [String: Any] {
                if identifiersList[identifier] != nil {
                    return self.instantiateViewController(withIdentifier: identifier)
                }
            }
            return nil
        }
    }
    

    Use this methods like this anywhere:

    if let viewController = self.storyboard?.instantiateVC(withIdentifier: "yourControllerID") {
                // Use viewController here
                viewController.view.tag = 0; // for example
            }
    

    or

        if let viewController = UIStoryboard(name: "yourStoryboardID", bundle: nil).instantiateVC(withIdentifier: "yourControllerID") {
            // Use viewController here
            viewController.view.tag = 0; // for example
        }
    

    Replace "yourControllerID" with your controller's ID.

提交回复
热议问题