从UIViewController打开SKScene时出现NSInvalidArgumentException错误

4

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

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

  • info.plist中删除Main_iphoneMain_ipad列表。
  • deployment info下的Main Interface中删除Main_iPhone.storyboard

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

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

    return YES;

3. Configuring SKScene in viewController.m

-(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:]: 无法识别的选择器发送到实例0x155854d0
*** 因未捕获异常“NSInvalidArgumentException”而终止应用程序,原因:“-[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: 抛出NSException之类的未捕获异常 (lldb)

备注:

  • 当我没有删除storyboards且未修改info.plist时,所有场景均工作正常。
  • 我正在通过编程方式创建所有场景和视图控制器。
  • 我已尝试在-(void)loadView下初始化self.view = [[SKView alloc]initWithFrame:self.view.frame]
2个回答

1
您已经指派了SKView* skView = (SKView*)self.view。 我认为self.view并不是SKView的子类,所以简单地将其类型转换为UIView会将您的SKView指向UIView。
虽然构建代码会成功,但是您肯定会得到运行时错误,因为您的SKView会发现self.view在nil指针SKView后面隐藏了它的真实身份(UIView)。
您可能希望将您的 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];
    }

1

出现异常是因为您试图在类型为UIView的视图上调用presentScene,而该方法属于SKView

默认情况下,Storyboard将self.view类设置为SKView。由于您删除了Storyboard并尝试正常初始化控制器,因此self.view将被初始化为UIView,而不是SKView

enter image description here

希望它有所帮助。

我理解你的观点,但我知道被接受的答案写得不好,这就是为什么它被编辑过的原因。此外,我没有使用任何XIB,所以我不得不创建一个SKView并将其作为子视图添加到我的视图控制器中,而不是完全继承我的视图控制器。希望这可以帮助到你。 - madLokesh
1
是的,这就是你要做的,@madLokesh :) - NightFury
这是我所做的。请查看更新后的答案。感谢您的努力,我非常感激。点赞表示我的感激之情。希望我的问题也能得到赞赏,并帮助其他访问者。 - madLokesh
感谢 @madLokesh 的赞赏... :) - NightFury

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接