gpt4 book ai didi

swift - 无法访问对象节点 Swift 中的属性

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

我在快速访问节点对象的自定义属性时遇到问题。我会尽力向你解释。

我创建了一个继承自 SkSpriteNode 的类,并创建了一个调用 (Has Gluten) 的属性

    init(foodName:  String, foodNote: String, foodImage: SKTexture, hasGluten: Bool) {
self.foodNote = foodNote
self.foodImage = foodImage
self.hasGluten = hasGluten
self.foodName = foodName

super.init(texture: foodImage, color: UIColor.clear, size: CGSize(width: 40, height: 40))
self.position = CGPoint(x: Int.random(in: 0..<355), y: 600)
self.name = self.foodName

}

直到这里好吧,但是当我将此节点添加到屏幕并主动触摸开始时,我无法访问此类中的属性 HasGluten 。它说我只能访问 native 属性,例如(名称、位置等)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch:UITouch = touches.first!
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if touchedNode.hasGluten == true { callfunction() } else {call another function}

}

这是我想要访问该属性的点。但是当我尝试访问 HasGluten 属性时,它没有给我。

如果有人能提供帮助,我会很高兴。谢谢

最佳答案

为了访问您的属性,您应该将节点对象转换为您的自定义类型:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch:UITouch = touches.first!
let positionInScene = touch.location(in: self)
guard let touchedNode = self.atPoint(positionInScene) as? CustomNode else { return }
if touchedNode.hasGluten == true { callfunction() } else {call another function}

}

相反,CustomNode 使用正确的类名称。

关于swift - 无法访问对象节点 Swift 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240445/

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