在swift中使用另一个类initilizer中的类(或实例)属性

时间:2016-07-27 22:44:25

标签: swift class sprite-kit initialization instantiation

我对Swift比较新,我想知道是否有办法在单独的类初始值设定项中引用类的属性?例如:如果我有一个具有属性Person的类position,是否有办法初始化Pants类,使其position与{{1}相同}}' S?这是我的代码:

Person

首先,我尝试引用 class Pants:SKSpriteNode{ init(){ let pants = SKTexture(imageNamed: "Sprites/pants.jpg") pants.setScale(0.5) super.init(texture: pants, color: UIColor.clearColor(), size: pants.size()) //self.position.x = aPerson.position.x + (aPerson.size.width / 2) //self.position.y = aPerson.position.y - (aPerson.size.height * 0.04) self.position = Person.getPos()//CGPoint(x: 200,y: 200) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } aPerson的实例,但我收到了错误:Person。我认为理解为什么在这种情况下引用一个实例没有多大意义 - 因为实例在引用时可能不存在?但我真的不知道这个错误信息意味着什么 - 任何澄清都会很棒。然后我想在Instance member aPerson cannot be used on type GameScene类中使用static getter方法,它只返回它的位置属性。这似乎也行不通。任何建议都很棒!

2 个答案:

答案 0 :(得分:2)

一种解决方案是在初始化程序中添加一个参数(正如Paul Griffiths在上面的评论中所建议的那样):

class Pants: SKSpriteNode {
    init(aPerson: Person) {
        let pants = SKTexture(imageNamed: "Sprites/pants.jpg")
        pants.setScale(0.5)

        super.init(texture: pants, color: UIColor.clearColor(), size: pants.size())

        self.position.x = aPerson.position.x + (aPerson.size.width / 2)
        self.position.y = aPerson.position.y - (aPerson.size.height * 0.04)
        self.position = aPerson.getPos()//CGPoint(x: 200,y: 200)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后,无论您想要创建Pants个实例,都必须传递一个人:

let somePerson = Person()
let pants = Pants(aPerson: somePerson)

答案 1 :(得分:1)

我认为裤子是人穿的吗?所以相反,工作相对而不是绝对。

让Pants成为人的子节点,然后你需要担心的是从Person的中心到Pant线的距离。如果这将始终是一个常数(如中心下方10个像素),那么硬编码。如果裤线改变,那么就像@Santa Claus建议的那样传递喘气线

====请在这里假设一些代码======

class Pants: SKSpriteNode {
    convenience init(pantline: Int) {

        self.init(imageNamed: "Sprites/pants.jpg")
        self.setScale(0.5) //Why?

        self.anchorPoint = CGPointMake(0.5,1)
        self.position.y = pantline
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    } 
    override init (texture: SKTexture, color: UIColor, size: CGSize)
    {
        super.init(texture: texture, color: color, size: size)
    }

=====================================

{{1}}

}