Calling method from viewcontroller to class xcode

随声附和 提交于 2019-12-11 09:52:30

问题


I don't know if it is possible, but I would like to call a view controller's method in a class object. I have method like this in my view controller's .m file:

-(void)showLeaderBoard
{
    GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
    if (leaderboardController != nil){
        leaderboardController.leaderboardDelegate = self;
        [self presentModalViewController: leaderboardController animated: YES];
    }
}

I would like to call that method in a SKScene file.


回答1:


One way to do this is called delegation. In a nutshell, you allow the view controller to be the delegate on the object, so when the object wants to do something the view controller does, it can tell its delegate (the view controller) when to do it.

Step 1: Create the delegate property on the object (in the objects .h file):

// be sure to import the view controller's header here
@property (nonatomic, retain) YourViewControllerClass *delegate;

Step 2: When you create the object in your view controller, set the view controller as the objects delegate:

SKScene *theScene = // however you create your scene object here
theScene.delegate = self;

Step 3: Expose whatever method you want the object to call in the view controller's header:

- (void)showLeaderBoard;

Step 4: When you want to, tell the object's delegate to do whatever you want it to (inside the SKScene .m file):

[self.delegate showLeaderBoard];


来源:https://stackoverflow.com/questions/25495831/calling-method-from-viewcontroller-to-class-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!