Swift - 必须调用超类SKSpriteNode错误的指定初始值设定项

时间:2014-08-06 15:25:23

标签: ios swift sprite-kit skspritenode designated-initializer

此代码适用于第一个XCode 6测试版,但在最新测试版中,它无效并且出现此类错误 Must call a designated initializer of the superclass SKSpriteNode

import SpriteKit

class Creature: SKSpriteNode {
  var isAlive:Bool = false {
    didSet {
        self.hidden = !isAlive
    }
  }
  var livingNeighbours:Int = 0

  init() {
    // throws: must call a designated initializer of the superclass SKSpriteNode
    super.init(imageNamed:"bubble") 
    self.hidden = true
  }

  init(texture: SKTexture!) {
    // throws: must call a designated initializer of the superclass SKSpriteNode
    super.init(texture: texture)
  }

  init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
  }
}

这就是这个课程的初始化方式:

let creature = Creature()
creature.anchorPoint = CGPoint(x: 0, y: 0)
creature.position = CGPoint(x: Int(posX), y: Int(posY))
self.addChild(creature)

我坚持了......最容易解决的是什么?

2 个答案:

答案 0 :(得分:73)

init(texture: SKTexture!, color: UIColor!, size: CGSize)是SKSpriteNode类中唯一指定的初始化程序,其余的都是便利初始化程序,因此您无法在它们上调用super。将您的代码更改为:

class Creature: SKSpriteNode {
    var isAlive:Bool = false {
        didSet {
            self.hidden = !isAlive
        }
    }
    var livingNeighbours:Int = 0

    init() {
        // super.init(imageNamed:"bubble") You can't do this because you are not calling a designated initializer.
        let texture = SKTexture(imageNamed: "bubble")
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
        self.hidden = true
    }

    init(texture: SKTexture!) {
        //super.init(texture: texture) You can't do this because you are not calling a designated initializer.
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
    }

    init(texture: SKTexture!, color: UIColor!, size: CGSize) {
        super.init(texture: texture, color: color, size: size)
    }
}

此外,我会将所有这些合并到一个初始化程序中。

答案 1 :(得分:9)

疯狂的东西..我不完全明白我是如何设法修复的......但是这样做有效:

convenience init() {
    self.init(imageNamed:"bubble")
    self.hidden = true
}

init(texture: SKTexture!, color: UIColor!, size: CGSize) {
    super.init(texture: texture, color: color, size: size)
}

convenience添加到init并删除init(texture: SKTexture!)