你好,我目前在 xCode 中使用 swift,我有一个随机数生成器,可以在 View 中生成一个随机点。
func randomInRange(lo: Int, hi : Int) -> Int {
return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
}
// x coordinate between MinX (left) and MaxX (right):
let randomX = randomInRange(Int(CGRectGetMinX(self.frame) * 2), Int(CGRectGetMaxX(self.frame)))
// y coordinate between MinY (top) and MidY (bottom):
let randomY = randomInRange(Int(CGRectGetMinY(self.frame) * 2), Int(CGRectGetMaxY(self.frame)))
let randomPoint = CGPoint(x: randomX , y: randomY)
我想全局使用这个变量,这样我就可以多次使用这个随机点,而不必每次都写出整个代码块。现在我知道您可以通过在 GameScene 类上方或在类和 viewDidLoad 之间声明它来创建一个全局变量
class GameScene: SKScene , SKPhysicsContactDelegate {
func randomInRange(lo: Int, hi : Int) -> Int {
return lo + Int(arc4random_uniform(UInt32(hi - lo + 1)))
}
// x coordinate between MinX (left) and MaxX (right):
let randomX = randomInRange(Int(CGRectGetMinX(self.frame) * 2), Int(CGRectGetMaxX(self.frame)))
// y coordinate between MinY (top) and MidY (bottom):
let randomY = randomInRange(Int(CGRectGetMinY(self.frame) * 2), Int(CGRectGetMaxY(self.frame)))
let randomPoint = CGPoint(x: randomX , y: randomY)
override func didMoveToView(view: SKView) {
/* Setup your scene here */
但是,当我将它放在同一个场景类之上时,我收到错误消息... “使用未解析的标识符自身” 当我把它放在 gameScene 类和 viewDidLoad 之间时,我得到了错误...... gameScene 没有名为 self 的成员。 如果可能的话,有没有办法用关于 View 的其他东西替换 self ,如果是这样,请回答。 谢谢!
最佳答案
在 GameScene 类上方声明全局函数,并将 self.frame
替换为 UIScreen.main.bounds
。
关于ios - 如何在 Swift 中创建一个使用 "self"的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29809643/