我最近尝试使用Xcode中的MainStoryboard.storyboard,到目前为止它非常好,我想知道为什么我以前从未使用它。在玩一些代码的时候,我碰到了一个障碍,我不知道如何解决这个问题。故事板和自定义初始化
当我alloc和初始化一个新的视图控制器(与我在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;
}
感谢。看起来疯狂的是,苹果公司没有提供一种方法来创建一个适用于故事板的定制'init'方法。 – jowie
我不知道为什么会说:“如果你所有的initWithCustomData方法都设置了一个实例变量,你应该手动设置它(不需要自定义inits或额外的方法)”。没有苹果公司的文件说明,所以我建议任何读者认为这个陈述仅仅是一个意见,而不是一个遵循的规则。 iOS中的大量初始化器甚至只有一个参数。 – zumzum
@zumzum Apple在示例代码中使用了在'prepareForSegue:sender:'方法中设置变量的做法。请参阅[EKReminderSuite]中的“AddTimedReminder.m”文件(https://developer.apple.com/library/prerelease/ios/samplecode/EKReminderSuite/Introduction/Intro.html#//apple_ref/doc/uid/TP40015203- Intro-DontLinkElementID_2)示例项目。 –