你的问题是你正在使用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.
From Swift 编程语言:属性,关于惰性存储属性:
惰性存储属性是指直到第一次使用时才计算其初始值的属性。
因此,当您使用titleLabel
in didMoveToView
, self
已完全初始化,可以安全使用self.view!.frame.maxX
(请参阅下文,了解如何在无需强制展开的情况下获得相同的结果view
).
Edit
看一下你的错误图片:
您的第一个问题是在使用惰性变量时需要显式声明属性的类型。其次,在使用惰性属性时需要显式引用 self:
lazy var label: UILabel =
UILabel(frame: CGRect(x: self.view!.scene!.frame.maxX, y: 5, width: 5, height: 5))
你可以通过不使用来清理它view
到达,得到scene
- 你已经得到了参考scene
- it's self
!
lazy var label: UILabel =
UILabel(frame: CGRect(x: self.frame.maxX, y: 5, width: 5, height: 5))