Paul
Paul

Reputation: 1159

Present a UIViewController from SKScene

I'm trying to present a UIViewController from a SKScene and I can't figure out how to do it. Most of what a Google search provides is how to present a share screen from a SKScene, but that is not what I'm trying to do. Just a regular View Controller that will have a button and a label (maybe a image as well).

Here's my code in my Intro.m. This is not the Gameplay scene, just a intro screen with a title, play button and a remove ads button:

#import "MyScene.h"
#import "Intro.h"
#import "PurchasedViewController.h"

@interface PurchasedViewController ()

-(id)initWithSize:(CGSize)size {

   if (self = [super initWithSize:size]) {

  .....

   SKSpriteNode *removeAds = [SKSpriteNode spriteNodeWithImageNamed:@"removeAds"];
     removeAds.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame)/6);
     removeAds.zPosition = 1;
     removeAds.name = @"RemoveAds";
    [self addChild:removeAds];
  }

 - (void)performTouches:(NSSet *)touches {    

  for (UITouch *touch in touches) {
    CGPoint pointInSKScene = [self.view convertPoint:[touch locationInView:self.view] toScene:self];
    SKNode *touchedNode = [self nodeAtPoint:pointInSKScene];

    if ([touchedNode.name isEqualToString:@"RemoveAds"]) {
        [self runAction:[SKAction playSoundFileNamed:@"enter.mp3" waitForCompletion:NO]];

        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
        UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"PurchasedViewController"];
        [self presentViewController:vc animated:YES completion:nil];
      }
    }
  }

The error Xcode gives me is "No visible @interface for Intro declares 'presentViewController: animated: completion'.

I'm a bit stumped because I haven't tried to present a UIViewController from a SKScene before and can't find a solution on the web.

Upvotes: 1

Views: 1109

Answers (1)

Paul
Paul

Reputation: 1159

I found a solution that is much simpler than most of the solutions out there:

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"PurchasedVC"];
//Call on the RootViewController to present the New View Controller
[self.view.window.rootViewController presentViewController:vc animated:YES completion:nil];

I also figured out an even simpler one liner if you create a segue in Storyboard and give it an identifier:

[self.view.window.rootViewController performSegueWithIdentifier:@"PurchasedViewController" sender:self];

Upvotes: 1

Related Questions