3

ゲームが終了するとスコアが表示されるアプリSpriteKitを xcode で作成しました。Facebook にスコアを投稿する機能を追加したいと考えています。ほとんどすべてのコードは、MyScene.mアクセスできない場所にありますpresentViewController。私の ViewController.m ファイルだけがそれにアクセスできるので、Myscene.m から Viewcontroller のインスタンス メソッドを呼び出してみましたが、それを行う方法が見つかりません。他のファイルからメソッドを呼び出すことがわかった唯一の方法+(void)は、私が思うクラスメソッドを使用することです。

Myscene.m:

    if (location.x < 315 && location.x > 261 && location.y < 404 && location.y > 361) {
 //if you click the post to facebook button (btw, location is a variable for where you tapped on the screen)

     [ViewController facebook];
                    }

ViewController.m:

+(void)facebook{

    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        SLComposeViewController *facebook = [[SLComposeViewController alloc] init];
        facebook = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [facebook setInitialText:@"initial text"];  
    }

    }

それは機能し、facebook クラス メソッドを正しく呼び出しましたが[self presentViewController:facebook animated:YES]、setInitialText ブラケットの後に置くと、次のエラーが表示されます。セレクター 'presentViewController:animated:' の既知のクラス メソッドはありません

ちなみに、presentViewControllerインスタンス メソッドで使用できますが、クラス メソッド内または Myscene ファイルからそのメソッドを呼び出すことはできません。別のファイルからインスタンス メソッドを呼び出す方法、またはpresentViewControllerクラス メソッドからアクセスする方法はありますか? ありがとう

4

1 に答える 1

3

ビュー コントローラーの参照を SKScene に渡すか、NSNotificationCenter代わりに使用することができます。私は後者を使用することを好みます。

まず、Social.framework をプロジェクトに追加したことを確認してください。

ソーシャル フレームワークをビュー コントローラーにインポートする#import <Social/Social.h>

次に、View Controller の viewDidLoad メソッドに次のコードを追加します。

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

次に、このメソッドを View Controller に追加します。

-(void)createPost:(NSNotification *)notification
{
    NSDictionary *postData = [notification userInfo];
    NSString *postText = (NSString *)[postData objectForKey:@"postText"];
    NSLog(@"%@",postText);

    // build your tweet, facebook, etc...
    SLComposeViewController *mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
    [self presentViewController:mySLComposerSheet animated:YES completion:nil];

}

SKScene の適切な場所 (勝ったゲーム、負けたゲームなど) に次のコードを追加します。

NSString *postText = @"I just beat the last level.";
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:postText forKey:@"postText"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"CreatePost" object:self userInfo:userInfo];

上記のコードは、テキストを含む NSNotification を送信し、View Controller がそれを取得して、指定されたメソッドを実行します。

于 2014-05-25T14:57:14.230 に答える