27

我最近尝试在 Xcode 中使用 MainStoryboard.storyboard,到目前为止一切顺利,我想知道为什么我以前从未使用过它。在玩一些代码时,我遇到了一个障碍,我不知道如何解决这个问题。

当我分配并初始化一个新的 ViewController(使用我在 ViewControllers 类中声明的自定义初始化)时,我会做这样的事情:

ViewController *myViewController = [[ViewController alloc] initWithMyCustomData:myCustomData];

然后在那之后我可以做类似的事情:

[self presentViewController:myViewController animated:YES completion:nil];

当我使用故事板时,我了解到切换到独立的 ViewController 需要一个标识符。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
[self presentViewController:myViewController animated:YES completion:nil];

在使用情节提要的同时,如何仍然使用 myViewController 的自定义初始化?

做这样的事情可以吗:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
myViewController.customData = myCustomData;
[self presentViewController:myViewController animated:YES completion:nil];




//MyViewController.m
- (id) initWithMyCustomData:(NSString *) data {
if (self = [super init]) {
    iVarData = data;
}
return self;
}
4

3 回答 3

20

我将创建一个执行自定义数据加载的方法。

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
[myViewController loadCustomData:myCustomData];
[self presentViewController:myViewController animated:YES completion:nil];

如果你的initWithCustomData方法只是设置一个实例变量,你应该手动设置它(不需要自定义初始化或额外的方法):

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
myViewController.iVarData = myCustomData;
[self presentViewController:myViewController animated:YES completion:nil];
于 2013-08-20T09:47:31.240 回答
17

您可以在 -init 方法中实例化视图控制器。

 - (instancetype)init
 {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

   self = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];

   if(self)
   {
    //default initialization

   }
   return  self;
 }

以及在您的自定义初始化方法中

 - (instancetype)initWithImages:(NSArray *)images
 {
   self = [self init];

   if(self)
   {
     self.images = images;
   }

   return  self;
 }
于 2016-02-25T06:41:11.870 回答
3

我的版本:

- (instancetype)initWithData (NSArray *)someData
 {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

   self = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];

   if(self)
   {
    //default initialization

   }
   return  self;
 }

...一个初始化器;)

于 2016-11-14T18:29:02.540 回答