如何在Swift中设置新的类文件

时间:2015-12-05 20:24:54

标签: ios swift class

我试图通过将一些代码移到Swift中的不同类来清理我的代码。但是,在设置课程时,我对初始化程序感到困惑。我想在设置一个新矩形时传递位置参数和大小参数。

    let rectangle = SKShapeNode(rectOfSize: CGSize(width:390, height:200))
    rectangle.position = CGPointMake(frame.midX-10, frame.midY + 50)
    rectangle.strokeColor = SKColor.blackColor()
    rectangle.glowWidth = 1.0
    rectangle.physicsBody = SKPhysicsBody(edgeChainFromPath: rectangle.path!)
    rectangle.physicsBody?.dynamic = false
    self.addChild(rectangle)

我的尝试:

class Walls: SKSpriteNode {
var size = SKShapeNode(rectOfSize: CGSize(width:390, height:200))

init(postition: CGPoint, size: CGSize) {
    super.init(color:SKColor.blackColor())
    self.size = SKShapeNode(rectOfSize: CGSize(width:390, height:200))
    self.position = CGPointMake(frame.midX-10, frame.midY + 50)
    self.strokeColor = SKColor.blackColor()
    self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
    self.physicsBody!.dynamic = false
}

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

1 个答案:

答案 0 :(得分:1)

class Walls: SKSpriteNode {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        didLoad()
    }

    func didLoad() {
        let rectangle = SKShapeNode(rectOfSize: CGSize(width:390, height:200))
        rectangle.position = CGPointMake(frame.midX-10, frame.midY + 50)
        rectangle.strokeColor = SKColor.blackColor()
        rectangle.glowWidth = 1.0
        rectangle.physicsBody = SKPhysicsBody(edgeChainFromPath: rectangle.path!)
        rectangle.physicsBody?.dynamic = false
    }
}