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

后端 未结 6 1369
-上瘾入骨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:15

    @Kevin's solution works. Here is a pretty the same piece of code for Swift 3 as function, that I am using in my code:

    func instantiateViewController(fromStoryboardName storyboardName: String, withIdentifier identifier: String) -> UIViewController? {
        let mainStoryboard = UIStoryboard(name: storyboardName, bundle: nil)
        if let availableIdentifiers = mainStoryboard.value(forKey: "identifierToNibNameMap") as? [String: Any] {
            if availableIdentifiers[identifier] != nil {
                if let poiInformationViewController = mainStoryboard.instantiateViewController(withIdentifier: identifier) as? UIViewController {
                    return viewController
                }
            }
        }
        return nil
    }
    

    Use this function as follows:

    if let viewController = self.instantiateViewController(fromStoryboardName: "YourStoryboardName", withIdentifier: "YourViewControllerStoryboardID") {
        // Here you are sure your viewController is available in the Storyboard
    } else {
        print("Error: The Storyboard with the name YourStoryboardName or the Storyboard identifier YourViewControllerStoryboardID is not available")
    }
    

提交回复
热议问题