我如何从其他类调用函数?斯威夫特,Xcode
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25528640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How i can call functions from other class? Swift, Xcode
提问by Artyom Chebotaryov
I have a class ACCreateObject. They have a function circlePhysicsDefault. I want to call this function other file by push the Button. In GameViewController i type:
我有一个 ACCreateObject 类。他们有一个函数 circlePhysicsDefault。我想通过按下按钮来调用这个函数的其他文件。在 GameViewController 我输入:
@IBAction func addOneCircle(sender: AnyObject) {
ACCreateObject.circlePhysicsDefault(ACCreateObject)
}
But i have a issue: '(ACCreateObject).Type' is not convertible to 'ACCreateObject'. How can i call the function? What am doing wrong?
但我有一个问题:“(ACCreateObject).Type”不能转换为“ACCreateObject”。我如何调用该函数?做错了什么?
Thanks!
谢谢!
ACCreateObject.swift
ACCreateObject.swift
class ACCreateObject: SKScene {
func circlePhysicsDefault() {
var Circle = SKShapeNode(circleOfRadius: 40)
Circle.position = CGPointMake(500, 500)
Circle.name = "defaultCircle"
Circle.strokeColor = SKColor.blackColor()
Circle.glowWidth = 10.0
Circle.fillColor = SKColor.yellowColor()
Circle.physicsBody = SKPhysicsBody(circleOfRadius: 40)
Circle.physicsBody.dynamic = true
self.addChild(Circle)
}
}
回答by Marc-Alexandre Bérubé
You are calling an instance method on a class object. You have two solutions :
您正在对类对象调用实例方法。您有两种解决方案:
Create a new instance and calls it's method
创建一个新实例并调用它的方法
ACCreateObject().circlePhysicsDefault()
OR
或者
Make it a class function
使其成为类函数
// In your class file
class func circlePhysicsDefault() {
....
}
And then call ACCreateObject.circlePhysicsDefault()
然后调用 ACCreateObject.circlePhysicsDefault()
回答by tudoricc
Not sure if I'm understanding you right but by what you are saying you want to call a method on the type instead on an object
不确定我是否理解你的意思,但根据你所说的,你想在类型上调用一个方法而不是在对象上
The first thing that comes to mind is this:
首先想到的是这个:
var x = ACCreateObject()
x.circlePhysicsDefault()
I think this is the way you should do this.I know there are options of making a class circlePhysicsDefault
我认为这是你应该这样做的方式。我知道有一些选项可以让一个类 circlePhysicsDefault