使用instantiateViewControllerWithIdentifier和performseguewithidentifier有什么区别?

这两种方法都允许我提出一个新的视图控制器(一个通过调用presentviewcontroller),所以我不明白两者之间的区别,什么时候应该使用它们。

他们都参考故事板相关的标识符。 主要区别是一个( performSegueWithIdentifer )基于一个segue的结束(segue指向的地方)实例化一个对象,而另一个( instantiateViewControllerWithIdentifier )基于VC的标识符(而不是segue) instantiateViewControllerWithIdentifier化一个唯一的VC。

故事板中的不同位置可以有多个具有相同标识符的segue,而故事板中的VC不能具有相同的标识符。

performSegueWithIdentiferinstantiateViewControllerWithIdentifier都用于从一个viewController移动到另一个viewController。 但是有这么多的差异….

  1. 第一种情况的标识符定义了一个类似push,modal,custom等的segue,用于执行从一个VC到另一个VC的特定types的转换。 例如。

     self.performSegueWithIdentifier("push", sender: self);` 

    其中“push”是push segue的标识符。

    第二种情况的标识符定义了一个类似于myViewController,myTableViewController,myNavigationController等的VC。第二个函数用于从storyboard中的一个VC到特定的VC(带有标识符)。 例如。

     var vc = mainStoryboard.instantiateViewControllerWithIdentifier("GameView") as GameViewController; self.presentViewController(VC, animated: true, completion: nil) ; 

    其中“GameView”是GameViewController的标识符。 这里创build一个GameViewController的实例,然后调用presentViewController函数去实例化的vc。

  2. 对于第一种情况,借助于segue标识符,可以将更多的variables值传递给下一个VC。 例如。

     override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "push") { let game = segue.destinationViewController as GameViewController game.value = self.myvalue // *value* is an Int variable of GameViewController class and *myvalue* is an Int variable of recent VC class. } } 

    这个function也称为self.performSegueWithIdentifier(“推”,发件人:自我); 被调用来将值传递给GameViewController。

    但在第二种情况下,可能直接,

     var vc = mainStoryboard.instantiateViewControllerWithIdentifier("GameView") as GameViewController; vc.value = self.myvalue; self.presentViewController(VC, animated: true, completion: nil) ;