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

Nio*_*lus 1 sprite-kit swift

我最近更新到Xcode 7 Beta,现在我收到一条错误消息"实例成员'视图'不能用于第5行的'GameScene'类型.任何人都有任何想法如何解决这个问题?另外,如果你想要额外的帮助,请参阅我的另一个问题:ConvertPointToView函数无法在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) {
}
}
Run Code Online (Sandbox Code Playgroud)

ABa*_*ith 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`.
Run Code Online (Sandbox Code Playgroud)

在这里你引用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.
Run Code Online (Sandbox Code Playgroud)

来自Swift编程语言:属性,在惰性存储属性上:

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

因此,在您使用titleLabeldidMoveToView,self已经完全初始化并且使用安全self.view!.frame.maxX(请参阅下文,了解如何在不需要强行打开的情况下实现相同的结果view).


编辑

看一下你的错误图片:

在此输入图像描述

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

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

你可以通过不使用view来清理这一点scene- 你已经有了参考scene- 它是self!

lazy var label: UILabel = 
    UILabel(frame: CGRect(x: self.frame.maxX, y: 5, width: 5, height: 5))
Run Code Online (Sandbox Code Playgroud)