Application tried to present a nil modal view controller on target “Current View Controller”解决方案

时间:2022-03-05 21:50:45

情景再现

1,自定义一个storyboard:

打开xcode,按下cmd+N,新建一个Storyboard--->next

Application tried to present a nil modal view controller on target “Current View Controller”解决方案

将新建立的storyboard命名为:TestViewController--->create

Application tried to present a nil modal view controller on target “Current View Controller”解决方案

在TestViewController.storyboard上加上一个label,其text为:Hello-ios

2,编写UIButton的UIControlEventTouchUpinside事件:

- (IBAction)btnClick:(id)sender {
//创建加载storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TestViewController" bundle:nil];
//将控制器关联到storyboard
_viewOfStoryboard = [storyboard instantiateInitialViewController];
_viewOfStoryboard.view.backgroundColor = [UIColor whiteColor];
[self dismissViewControllerAnimated:YES completion:nil];
[self presentViewController:_viewOfStoryboard animated:YES completion:nil];
}

运行操作如下:

Application tried to present a nil modal view controller on target “Current View Controller”解决方案

在加载自定义storyboard界面遇到如下问题

Application tried to present a nil modal view controller on target “Current View Controller”解决方案

错误原因:应用程序视图向目标展示一个空模式形态的视图控制器,简单的说,storyboard中的视图控制器是空的。

3,解决方案:

  • *上给了相关回答(下面是个人的翻译,如有误请指出)

Check the identifier of the viewcontroller, if it is the same that you mentioned in storyboard。

  • 检查viewcontroller上的标识符,确保它在storyboard上是独一无二的。

Make sure that your buddiesOrFacebook is not nil. Set a breakpoint on that line and on the debug area at the bottom see whether the object is not nil. If it is nil then problem lies in the storyboard connection。

  • 确保你的buddies或者facebook(这句话没有理解)不是空的。可以设置断点进行调试,如果该对象是空的,那么就是storyboard的连接出现了问题。

If your current viewcontroller is not launched from storyboard then get storyboard object like this :

如果当前的viewcontroller没有开始加载,可以参考下面的标准写法:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController * buddiesOrFacebook = [storyboard instantiateViewControllerWithIdentifier:@"BuddiesFBFriends"] ;
[self presentViewController:buddiesOrFacebook animated:YES completion:nil];

上面的解决方案并没有解决我的问题,于是采取了第二套解决方案。

打开TestViewController.storyboard视图,操作如下:

Application tried to present a nil modal view controller on target “Current View Controller”解决方案

选中Is Initial View Controller,确保viewcontroller被初始化。

4,结果:

最后运行正确,如下图:

Application tried to present a nil modal view controller on target “Current View Controller”解决方案