什么是StoryBoard ID,我该如何使用它?

RTB*_*RTB 109 xcode storyboard uiviewcontroller ios

我是IOS的新手,最近开始使用Xcode 4.5.我看到每个viewController我都可以设置一些身份变量,包括故事板ID.这是什么以及如何使用它?

在此输入图像描述

我开始在stackoverflow上搜索,但找不到任何解释.我认为这不仅仅是一些愚蠢的标签,我可以设置为记住我的控制器吗?它有什么作用?

Eri*_*ric 130

故事板ID是一个String字段,您可以使用该字段创建基于该Storyboard ViewController的新ViewController.一个示例用法来自任何ViewController:

//Maybe make a button that when clicked calls this method

- (IBAction)buttonPressed:(id)sender
{
    MyCustomViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];

   [self presentViewController:vc animated:YES completion:nil];
}
Run Code Online (Sandbox Code Playgroud)

这将基于您命名为"MyViewController"的故事板ViewController创建一个MyCustomViewController,并将其显示在当前View Controller之上

如果您在app代理中,则可以使用

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                         bundle: nil];
Run Code Online (Sandbox Code Playgroud)

编辑:斯威夫特

@IBAction func buttonPressed(sender: AnyObject) {
    let vc = storyboard?.instantiateViewControllerWithIdentifier("MyViewController") as MyCustomViewController
    presentViewController(vc, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

编辑Swift> = 3:

@IBAction func buttonPressed(sender: Any) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "MyViewController") as! ViewController
    present(vc, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
Run Code Online (Sandbox Code Playgroud)


Tai*_*sam 11

要添加到Eric的答案并为Xcode 8和Swift 3更新它:

故事板ID完全符合名称的含义:它标识.只是它识别故事板文件中的视图控制器.这是故事板知道哪个视图控制器是哪个.

现在,不要被名字搞糊涂.故事板ID不能​​识别"故事板".根据Apple的文档,故事板"代表了应用程序全部或部分用户界面的视图控制器." 因此,当你有类似下图的内容时,你有一个名为Main.storyboard的故事板,它有两个视图控制器,每个视图控制器都可以给出一个故事板ID(它们在故事板中的ID).

在此输入图像描述

您可以使用视图控制器的故事板ID来实例化并返回该视图控制器.然后,您可以按照自己的意愿操纵并呈现它.要使用Eric的示例,假设您想要在按下按钮时显示带有标识符"MyViewController"的视图控制器,您可以这样做:

@IBAction func buttonPressed(sender: Any) {
    // Here is where we create an instance of our view controller. instantiateViewController(withIdentifier:) will create an instance of the view controller every time it is called. That means you could create another instance when another button is pressed, for example.
    let vc = storyboard?.instantiateViewController(withIdentifier: "MyViewController") as! ViewController
    present(vc, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

请注意语法的变化.