gpt4 book ai didi

swift - 使用超出其范围的变量

转载 作者:行者123 更新时间:2023-11-30 10:14:54 25 4
gpt4 key购买 nike

我希望访问其范围之外的变量。 (发布了相关代码片段)。在 @IBAction 中,无法识别 sphereNode.runAction(moveUp)。

我不能简单地将 sphereNode 声明为全局,因为它依赖于 sphereGeometry 声明。

override func viewDidLoad() {
super.viewDidLoad()

//Added our first shape = sphere
let sphereGeometry = SCNSphere(radius: 1.0)
let sphereNode = SCNNode(geometry: sphereGeometry)
sphereNode.position = SCNVector3Make(0, 0, 0)
sphereGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()
sphereGeometry.firstMaterial!.specular.contents = UIColor.whiteColor()
scene.rootNode.addChildNode(sphereNode)
}

@IBAction func animateButton(sender: AnyObject) {
let moveUp = SCNAction.moveByX(0.0, y: 1.0, z: 0.0, duration: 1.0)
sphereNode.runAction(moveUp)
}

}`

初学者程序员,所以请简单的解释 - 提前致谢。

最佳答案

这里您需要的是一个实例变量。

变量不能在其范围之外使用(最终你会发现这是一件非常棒的事情)。但我们可以扩展变量的范围:

class YourViewController: UIViewController {
var sphereNode: SNNode?

override func viewDidLoad() {
super.viewDidLoad()

//Added our first shape = sphere
let sphereGeometry = SCNSphere(radius: 1.0)
self.sphereNode = SCNNode(geometry: sphereGeometry)
self.sphereNode?.position = SCNVector3Make(0, 0, 0)
sphereGeometry.firstMaterial!.diffuse.contents = UIColor.redColor()
sphereGeometry.firstMaterial!.specular.contents = UIColor.whiteColor()
scene.rootNode.addChildNode(sphereNode)
}

@IBAction func animateButton(sender: AnyObject) {
let moveUp = SCNAction.moveByX(0.0, y: 1.0, z: 0.0, duration: 1.0)
self.sphereNode?.runAction(moveUp)
}
}

关于swift - 使用超出其范围的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30733031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com