ios - 如何在 Swift 中创建一个使用 "self"的全局变量

标签 ios swift sprite-kit global-variables

你好,我目前在 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/

相关文章:

ios - performSegue(withIdentifier.......) 不工作

ios - 动态 UICollectionView 单元格框架

python - 如何使用 api 中的 header key 在 iOS Swift 中验证 URL?

sprite-kit - Sprite Kit 不同部分的不同重力

ios - 如何删除 socket 的所有引用

ios - 具有 anchor 样式自动布局约束的 UIButtons 未显示

ios - 如何从 UIImagePicker 推送到 UIViewController

ios - 如何自动关闭 SFSafariViewController?

ios - 平移手势识别器选择器不起作用

ios - 表达式类型(imageNamed : String) is ambiguous without more context