使用instantiateViewControllerWithIdentifier和performSegueWithIdentifier之间有什么区别?

8

这两种方法都可以让我呈现一个新的视图控制器(一种是通过调用presentviewcontroller),因此我不明白它们之间的区别以及何时应该使用它们。


instantiateViewControllerWithIdentifier做其名称所示的事情; 它实例化一个视图控制器,仅此而已。它不会呈现一个视图控制器。 - rdelmar
@rdelmar 我已经回复了你的评论,为你澄清了。 - Michael
2个回答

9

它们都引用了与故事板相关的标识符。主要区别在于,一个(performSegueWithIdentifer)根据segue的终点(即segue指向的位置)实例化一个对象,而另一个(instantiateViewControllerWithIdentifier)根据VC的标识符(而不是segue)实例化一个唯一的VC。

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


由于它们基本上做相同的事情,那么在什么情况下会更倾向于使用其中一个而不是另一个呢?此外,在采用程序化布局的项目中,哪种方法被广泛使用?我猜当您想要特定的UX过渡类型时,您将使用 performSegueWithIdentifer,因为 instantiateViewControllerWithIdentifier 只是一个普通的转换,对吧? - Edison
1
通常我认为大多数人会使用performSegueWithIdentifer,因为segue定义了流程。instantiate...使得故事板布局更加不确定(因为你正在用代码定义转换)。如果布局是以编程方式完成的,则通常都不会使用任何一个。只需创建一个类实例并呈现它:例如 let vc = FooVC() ... self.present(vc) - Firo

8

performSegueWithIdentifierinstantiateViewControllerWithIdentifier都用于从一个viewController移动到另一个viewController。但是它们之间有很大的区别....

  1. The identifier of the 1st case defines a segue like push, modal, custom etc which are used to perform a specific type of transition from one VC to another VC. eg.

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

    where "push" is an identifier of a push segue.

    The identifier of the 2nd case defines a VC like myViewController, myTableViewController, myNavigationController etc. 2nd function is used to go to the specific VC ( with identifier.) from a VC in the storyBoard. eg.

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

    where "GameView" is the identifier of GameViewController. Here a instance of GameViewController is created and then the function presentViewController is called to go to the instantiated vc.

  2. For the 1st case with the help of segue identifier u can pass one are more values of variables to the next VC. eg.

    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.
        }
    }
    

    This funcion is also called when self.performSegueWithIdentifier("push", sender: self); is called to pass the value to GameViewController.

    But in 2nd case it possible directly like,

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接