我最近尝试使用Xcode中的MainStoryboard.storyboard并且到目前为止它已经相当不错了,我想知道为什么我以前从未使用它。在玩一些代码时遇到了障碍,我不知道如何解决这个问题。
当我分配并初始化一个新的ViewController(我在ViewControllers类中声明了一个自定义init)时,我会这样做:
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;
}
答案 0 :(得分:18)
我只想创建一个自定义数据加载的方法。
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
[myViewController loadCustomData:myCustomData];
[self presentViewController:myViewController animated:YES completion:nil];
如果你的initWithCustomData
方法都设置了一个实例变量,你应该手动设置它(不需要自定义inits或额外的方法):
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyViewController *myViewController = [storyboard instantiateViewControllerWithIdentifier:@"MyViewControllerIdentifier"];
myViewController.iVarData = myCustomData;
[self presentViewController:myViewController animated:YES completion:nil];
答案 1 :(得分:17)
您可以在-init方法中实例化viewcontroller。
- (instancetype)init
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
self = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
if(self)
{
//default initialization
}
return self;
}
和你的自定义init方法
- (instancetype)initWithImages:(NSArray *)images
{
self = [self init];
if(self)
{
self.images = images;
}
return self;
}
答案 2 :(得分:2)
我的版本:
- (instancetype)initWithData (NSArray *)someData
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
self = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
if(self)
{
//default initialization
}
return self;
}
......一个初始化程序;)