【问题标题】:How can I call a method from ViewController?如何从 ViewController 调用方法?
【发布时间】:2014-10-13 10:34:51
【问题描述】:

是否可以在 Swift 中从 ViewController 调用方法(在 Gamescene 中编写)? 我阅读了有关协议、委托或继承的信息,但我看到的所有教程都没有显示这种情况。

感谢您的帮助。

【问题讨论】:

  • 你在哪里尝试调用该方法?
  • 我正在尝试从我的 ViewController 调用计时器方法。定时器方法写的是GameScene。

标签: inheritance methods swift delegates protocols


【解决方案1】:

试试这个。

在 ViewController 类中

#import "Gamescene.h"

Gamescene *obj = [[Gamescene alloc] init];

[Gamescene methodName];

别忘了在 Gamescene.h 文件中添加方法名..

在 Swift 中

class SomeClass {
    class func someTypeMethod() {
    // type method implementation goes here
}

}

SomeClass.someTypeMethod()

你可以学习here苹果文档。

【讨论】:

  • 我用swift编码。我看到没有导入语句。代码有区别吗?
  • 我试过了:GameScene.startTimer() 但我有一条消息错误:“在调用中缺少参数 #1 的参数”
  • startTimer() 方法是否有任何参数要传递?我的意思是需要在此方法中传递任何输入?
【解决方案2】:

可以通过以下方式调用方法,

  • 如果一个方法在你的视图控制器中,那么你可以用self调用它,查看问题寻求帮助,How can I call a method in Objective-C?

    [self yourMethodName];

    如果是类方法,则[ClassName yourMethodName];

  • 如果您的方法来自其他类,只需 #import 那个类,就像 #import "someclass.h" 一样,创建该类的对象并调用,检查此以获得更多帮助,Objective C - Call method from another class

    someclass *obj = [[someclass alloc] init];

    [obj methodName];

    如果它是一个类方法,那么[someclass methodName];检查问题寻求帮助,calling class methods objective c

  • 有委托,如果你有 someclass 的自我委托,那么在 someclass 你可以这样称呼它,检查问题,How do I create delegates in Objective-C?

    if(self.delegate && [self.delegate respondsToSelector(methodName)]) { [self.delegate methodName]; }

    在你的视图控制器中你必须这样写,

    someclass *obj = [[someclass alloc] init]; obj.delegate = self;

    - (void)methodName { //call when delegate calls it. }

  • 另一种方法是使用NSNotificationCenter,请参阅此问题以获取详细帮助,Send and receive messages through NSNotificationCenter in Objective-C?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    相关资源
    最近更新 更多