问题
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