实例成员'查看'不能用于类型' GameScene'

时间:2015-09-12 23:51:32

标签: swift sprite-kit

我最近更新到Xcode 7 Beta,现在我收到一条错误消息"实例成员'查看'不能用于类型' GameScene'对于第5行。任何人有任何想法如何解决这个问题?另外,如果您想要更多帮助,请参阅我的另一个问题:ConvertPointToView Function not working in Swift Xcode 7 Beta

import SpriteKit

class GameScene: SKScene {

var titleLabel: StandardLabel = StandardLabel(x: 0, y: 0, width: 250, height: 80, doCenter: true, text: "Baore", textColor: UIColor.redColor(), backgroundColor: UIColor(white: 0, alpha: 0), font: "Futura-CondensedExtraBold", fontSize: 80, border: false, sceneWidth: view.scene.frame.maxX)

override func didMoveToView(view: SKView) {
    self.scene?.size = StandardScene.size
    self.view?.addSubview(titleLabel)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in (touches ) {
        let location = touch.locationInNode(self)
    }
}

override func update(currentTime: CFTimeInterval) {
}
}

1 个答案:

答案 0 :(得分:9)

您的问题是在self实例完全初始化之前,您正在使用GameScene。如果你看一下第5行的结尾:

var titleLabel = StandardLabel(..., sceneWidth: view.scene.frame.maxX) 
// Would be a good idea to use `let` here if you're not changing `titleLabel`.

此处您引用了self.view

要解决这个问题,我会懒洋洋地初始化titleLabel

lazy var titleLabel: StandardLabel = StandardLabel(..., sceneWidth: self.view!.scene.frame.maxX) 
// You need to explicitly reference `self` when creating lazy properties.
// You also need to explicitly state the type of your property.

来自The Swift Programming Language: Properties,关于延迟存储的属性:

  

惰性存储属性是一个属性,其初始值在第一次使用之前不会计算。

因此,当您在titleLabel中使用didMoveToView时,self已完全初始化,并且使用self.view!.frame.maxX是安全的(请参阅下文了解如何实现相同目标)结果而不需要强制解包view)。

修改

看一下你的错误图片:

enter image description here

您的第一个问题是在使用惰性变量时需要显式声明属性的类型。其次,在使用惰性属性时需要明确引用self:

lazy var label: UILabel = 
    UILabel(frame: CGRect(x: self.view!.scene!.frame.maxX, y: 5, width: 5, height: 5))

你可以通过不使用viewscene来清理这一点 - 你已经获得了对scene的引用 - 它是self

lazy var label: UILabel = 
    UILabel(frame: CGRect(x: self.frame.maxX, y: 5, width: 5, height: 5))