查看层次结构错误 - 尝试在新故事板中打开新的视图控制器

时间:2016-08-10 15:02:21

标签: ios swift uiviewcontroller uistoryboard

我遇到了viewheirarchy错误 - 尝试在新的故事板中打开一个新的视图控制器。

    override func viewDidLoad() {  
       super.viewDidLoad()

       if type == .Products {             
            self.presentViewController( UIStoryboard(name: "Fold", bundle: nil).instantiateViewControllerWithIdentifier("MainTableViewController") as! UITableViewController, animated: true, comp
       }
     }

1 个答案:

答案 0 :(得分:1)

我建议创建一个私有var

private var storyboard = UIStoryboard(name: "Fold", bundle: NSBundle.mainBundle())

创建一个功能

func showYourViewController() throws -> UINavigationController {
    if let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController {
      if let mainTableViewController = navigationController.topViewController as? MainTableViewController {
        mainTableViewController.delegate = self
      } else {
        throw StoryboardError.InvalidCast
      }
      return navigationController
    } else {
      throw StoryboardError.InvalidCast
    }
}

现在你可以使用它了

override func viewDidLoad() {  
   super.viewDidLoad()

   if type == .Products {             
    do {
        let yourViewController = try showYourViewController()
        setRootViewController(yourViewController)
    } catch StoryboardError.InvalidCast {
        print("Your View Controller was not of the expected type")
    } catch _ {
        print("Some other error occurred...")
    }
   }
 }

这是StoryboardError枚举

enum StoryboardError: ErrorType {
    case InvalidCast
}