从ViewController到类Xcode的调用方法 [英] Calling method from viewcontroller to class xcode

查看:99
本文介绍了从ViewController到类Xcode的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否可能,但是我想在类对象中调用视图控制器的方法.我的视图控制器的.m文件中有这样的方法:

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];
    }
}

我想在SKScene文件中调用该方法.

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

推荐答案

一种实现此目的的方法称为委托.简而言之,您可以将视图控制器作为对象的委托,因此,当对象要执行视图控制器要执行的操作时,它可以告诉其委托(视图控制器)何时执行.

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.

步骤1: 在对象(在.h文件中)上创建委托属性:

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;

步骤2: 在视图控制器中创建对象时,将视图控制器设置为对象委托:

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;

第3步: 在视图控制器的标题中公开您希望对象调用的任何方法:

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

- (void)showLeaderBoard;

第4步: 想要的时候,告诉对象的代理做你想做的任何事情(在SKScene .m文件中):

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];

这篇关于从ViewController到类Xcode的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆