如何在另一个类中访问扩展的 var



我正在使用雪碧套件。我想用设置类更改主类的按钮图片。如何使扩展中的变量(来自设置类)可用于主类?

这是扩展:

extension ChangingDots {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    for touch in touches{
        let locationUser = touch.location(in: self)
        if atPoint(locationUser) == DCButton {
     var blackdot = SKSpriteNode(imageNamed: "AppIcon") //<--var I want to use

        }
    }

}
}

以下是主类中的用法:

    blackdot.setScale(0.65)
    blackdot.position = CGPoint(x: CGFloat(randomX), y: CGFloat(randomY))
    blackdot.zPosition = 1
    self.addChild(blackdot)

有没有人有更好的主意将一个类的按钮图片从另一个类更改?

如果要在主类中使用变量,则需要在主类中创建该变量。 扩展旨在扩展功能,这意味着函数和计算属性。

要了解更多信息,请参阅此文档:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

在这里补充一下,有一些方法可以"解决方法"在扩展中添加存储的属性。 这是一篇描述如何做到这一点的文章:https://medium.com/@ttikitu/swift-extensions-can-add-stored-properties-92db66bce6cd

但是,如果是我,我会将该属性添加到您的主类中。 扩展旨在扩展类的行为。 使主类依赖于您的扩展似乎不是正确的设计方法。

如果要将其设为私有,可以使用 fileprivate,以便扩展可以访问它,但保持其"私有"访问权限。例如:

fileprivate var value: Object? = nil

抱歉,您让我意识到您无法在扩展中添加存储的属性。只能添加计算属性。可以将 blackdot var 添加为计算属性,也可以在主类而不是扩展中声明它。如果要尝试计算方式,请使用以下命令:

extension ChangingDots { 
   var blackdot:Type? { // Replace Type with SKSpriteNode type returned
       return SKSpriteNode(imageNamed: "AppIcon")
   }
   override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
     super.touchesBegan(touches, with: event)
     for touch in touches {
       let locationUser = touch.location(in: self)
       if atPoint(locationUser) == DCButton {
         blackdot = SKSpriteNode(imageNamed: "AppIcon") //<--var I want to use
       }
     }
   }
}

这样,您的blackdot变量只能获取,而不能设置。如果你想添加设置它的可能性,你需要添加一个像这样的二传手:

var blackdot:Type? { // Replace Type with SKSpriteNode type returned
   get {
       return SKSpriteNode(imageNamed: "AppIcon")
   }
   set(newImage) {
       ...
   }
}

最新更新