objective-c – 从UIViewController打开SKScene时出现NSInvalidArgumentException

我正在创建我的第一个SpriteKit游戏,这就是我想要做的:

1.删​​除默认的Main_iphone和Main_ipad故事板

>从info.plist中删除Main_iphone和Main_ipad列表.
>从主界面下删除Main_iPhone.storyboard
        部署信息.

2.在didFinishLaunchingWithOptions下的AppDelegate.m中添加以下代码

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[CMViewController alloc] init];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    return YES;

3.在viewController.m中配置SKScene

-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    //Configure the view.
    SKView* skView = (SKView*)self.view;
    //Create and configure the scene.
    SKScene* scene = [CMHomeScene sceneWithSize:skView.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;
    //Present the scene.
    [skView presentScene:scene];
 }

运行时错误

-[UIView presentScene:]: unrecognized selector sent to instance 0x155854d0
*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[UIView presentScene:]: unrecognized selector sent to instance 0x155854d0’
**** First throw call stack:
(0x2c3eac1f 0x39b95c8b 0x2c3f0039 0x2c3edf57 0x2c31fdf8 0x10883d 0x2f8a7433 0x2f2cfa0d 0x2f2cb3e5 0x2f2cb26d 0x2f2cac51 0x2f2caa55 0x2fb0b1c5 0x2fb0bf6d 0x2fb16379 0x2fb0a387 0x32b770e9 0x2c3b139d 0x2c3b0661 0x2c3af19b 0x2c2fd211 0x2c2fd023 0x2f90e3ef 0x2f9091d1 0x10c2d1 0x3a115aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

PS:

>当我不删除故事板和修改info.plist时,我的所有场景都正常工作.
>我正在以编程方式创建所有场景和查看控制器.
>我尝试过初始化
 self.view = [[SKView alloc] initWithFrame:self.view.frame]在 – (void)loadView下

最佳答案 您已分配SKView * skView =(SKView *)self.view.

我相信self.view不是SKView的子类,所以简单地进行类型转换会将你的SKView指向UIView.

虽然构建代码会很成功,但你肯定会得到运行时错误,因为你的SKView会发现self.view隐藏了它的真实身份(UIView)在一个零指针SKView后面.

您可能想要将3.配置视图更改为以下内容:

    - (void)viewWillLayoutSubviews 
    { 
    // Configure the view. 
    SKView* skView = [[SKView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    // Create and configure the scene. 
    SKScene* scene = [CMHomeScene sceneWithSize:skView.bounds.size]; 
    scene.scaleMode = SKSceneScaleModeAspectFill; 
    // Present the scene. 
    [skView presentScene:scene]; 
[self.view addSubview:skView];
    }
点赞