从Objective-C初始化Swift故事板

时间:2017-01-25 16:30:35

标签: ios objective-c swift xcode storyboard

我试图将Swift中的新故事板添加到旧的Objective-C应用程序中:

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard01" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"OnboardingViewController"];
[self presentViewController:vc animated:YES completion:NULL];

使用Swift故事板:

Onboarding Storyboard

我总是收到错误:

  

'找不到名为' MainStoryboard01'的故事板in bundle NSBundle< ... / Developer / CoreSimulator / Devices / 753636C1-ABB5-4D6E-B184-5C4638FB2CE9 / data / Containers / Bundle / Application / 398410C0-BB2C-4574-B058-95D30F8D1B5D / Credit Call.app> (加载)'

调用swift类     TestClass * instance = [TestClass new];     [instance testFunction];

通常有效。知道如何在Objective-C应用程序中调用swift storyboard +它的swfit控制器吗?

//编辑:

我终于开始工作了:

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Onboarding" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"MainStoryboard01"];

但在下一行

[self presentViewController:vc animated:YES completion:NULL];

我收到此错误:

  

***由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' - [MyAppDelegate presentViewController:animated:completion:]:无法识别的选择器发送到实例0x6080000b3b60'

有什么想法吗?我需要用故事板替换它:

Registration *reg = [[Registration alloc] init];
registrationNav = [[UINavigationController alloc] initWithRootViewController:reg];
[reg release];
[self.mainBackgroundView addSubview:[registrationNav view]];

=> https://codepaste.net/jkfras我添加了MyAppDelegate.m的骨架

2 个答案:

答案 0 :(得分:1)

您在此处犯了错误,MainStoryboard01您使用可以调用Storyboard Identifer的{​​{1}}设置了instantiateViewControllerWithIdentifier。它不是另一个故事板名称。所以它应该是这样的。

enter image description here

//You need to put storyboard name here the check the image for more detail
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [sb  instantiateViewControllerWithIdentifier:@"MainStoryboard01"];
[self presentViewController:vc animated:YES completion:nil];

编辑:尝试这种方式。

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *vc = [sb  instantiateViewControllerWithIdentifier:@"MainStoryboard01"];
[self.mainBackgroundView addSubview:[vc view]];

答案 1 :(得分:1)

如果你想引用故事板,那么你应该使用它的名字,所以如果你的故事板有一个名字" MyNewStoryboard" (MyNewStoryboard.storyboard)然后创建其引用的正确方法是这样的:

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MyNewStoryboard" bundle:nil];

不要在这里使用故事板ID。您刚刚在控制器属性中设置的故事板ID是控制器的标识符。所以你可以这样使用它:

UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"MainStoryboard01"];

将新控制器的故事板ID更改为更具信息性的内容,例如" OnboardingViewController",然后将故事板文件名放在第一行后,您的代码就可以了。