如何通过代码从SKScene到UIViewController?

我想要的只是当用户触摸skscene中的skspritenode时,它会转到不同的视图,如performseguewithidentifier 。 谢谢你的帮助。 我可以发布代码,但它似乎是一个通用的问题,所以我觉得你不需要任何。 顺便说一下,我已经想出了如何检测敲击skspritenode。 我一直在看这个很长时间,我很难过。 请帮忙。

您不能在SKScene中显示viewController,因为它实际上只是在SKView上呈现。 你需要一种方法来发送一条消息到SKView的viewController,这反过来会呈现viewController。 为此,您可以使用委派或NSNotificationCenter。

代表团

将以下协议定义添加到您的SKScene的.h文件中:

 @protocol sceneDelegate <NSObject> -(void)showDifferentView; @end 

并在界面中声明委托属性:

 @property (weak, nonatomic) id <sceneDelegate> delegate; 

然后,在您想要展示共享屏幕的位置,使用以下行:

 [self.delegate showDifferentView]; 

现在,在你的viewController的.h文件中,实现这个协议:

 @interface ViewController : UIViewController <sceneDelegate> 

而且,在.m文件中,在呈现场景之前添加以下行:

 scene.delegate = self; 

然后在那里添加下面的方法:

 -(void)showDifferentView { [self performSegueWithIdentifier:@"whateverIdentifier"]; } 

NSNotificationCenter

保持-showDifferentView方法,如前面的替代方法中所述。

将viewController作为侦听器添加到它的-viewDidLoad方法中的通知中:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showDifferentView) name:@"showDifferenView" object:nil]; 

然后,在你想要显示这个viewController的场景中,使用这一行:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"showDifferentView" object:nil]; 

我build议以下选项:(这在你的场景中)

 -(void)presentViewController{ MyViewController *myController = [[MyViewController alloc]init]; //Or instantiate any controller from the storyboard with an indentifier [self.view.window.rootViewController presentViewController:myController animated: YES options: nil]; } 

然后在你的视图控制器中,当你想解雇它时,做一些这样的事情:

 -(void)dismissItself:(id)sender { [self dismissViewControllerAnimated:YES completion:nil]; } 

这个选项的好处是你不需要存储你的视图,因为只要你在场景中,任何时候你都可以初始化它,导入viewcontroller的代码。

让我知道如果它的作品

ZeMoon,很好的答案,但如果多个场景想要显示相同的视图控制器,例如一些设置屏幕呢? 你不想定义多个场景委托协议来做同样的事情。

另一个想法是定义一个单一的协议,为您处理不同的视图控制器的演示文稿:

 @protocol ScreenFlowController <NSObject> - (void)presentSettingsScreenFromScene:(SKScene *)scene; - (void)presentCreditsScreenFromScene:(SKScene *)scene; @end 

场景参数可以用来根据你来自哪里做出决定。

您的游戏(或任何其他对象)的视图控制器实现该协议。 所有显示不同屏幕的场景都会收到对控制器的弱引用:

 @property (nonatomic, weak) id<ScreenFlowController> screenFlowController;