ios - SpriteKit swift : SKView returning nil

标签 ios swift swift4

我正在使用 spritekit 制作游戏。我在我的游戏中使用了一个操纵杆,它在一个名为“操纵杆”的单独 SKNode 类中声明。

在这个类中,我向类中的 View 添加了一个 UIGesturerecongiser。在构造方法中,其中一个参数是从游戏场景传来的 SKView。

Joystick 类中的构造方法:

 init(colour: UIColor, position: CGPoint, skView: SKView) {
    //constructor method
    self.colour = colour;
    self.parentposition = position;
    self.view = skView;

    super.init();

    //setup properties
    //user interaction is needed to allow touches to be detected
    self.isUserInteractionEnabled = true;
    //setup
    setup();
}

在游戏场景中,我这样初始化类:

class GameScene: SKScene {

     func setupJoyStick() {
        let joystick1 = Joystick(colour: UIColor.red, position: CGPoint(x: screenwidth / 3, y: screenwidth / 10 * 1.5), skView: self.view!)
        self.addChild(joystick1)
    }
}

错误:

当我运行我的应用程序时,我收到一个错误,因为“self.view”返回 nil 并且因为它被强制解包,它导致了一个 fatal error 。

定义View的地方:

if let scene = GKScene(fileNamed: "GameScene") {

        // Get the SKScene from the loaded GKScene
        if let sceneNode = scene.rootNode as! GameScene? {

            // Copy gameplay related content over to the scene
            sceneNode.entities = scene.entities
            sceneNode.graphs = scene.graphs

            // Set the scale mode to scale to fit the window
            sceneNode.scaleMode = .aspectFill
            sceneNode.size = view.bounds.size
            // Present the scene
            if let view = self.view as! SKView? {

                view.presentScene(sceneNode)

                view.ignoresSiblingOrder = true

                view.showsFPS = true
                view.showsNodeCount = true
            }
        }
    }

附加信息:

我正在使用:

  • Xcode 9.2
  • swift 4
  • SpriteKit

我正在测试它:

  • iPhone 6s
  • 最新版本的 IOS(非测试版),最新公开发布。

有人可以解释为什么会发生这种情况以及如何解决这个问题。

在此先致谢,如有任何帮助,我们将不胜感激。

最佳答案

看起来您正在尝试获取 SKSceneview 属性,但它是零。这是因为你没有呈现 SKScene

很遗憾,我没有使用过SpriteKit,但您可以找到有关view 属性的信息here关于SKScene here .

关于ios - SpriteKit swift : SKView returning nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545754/

相关文章:

iOS Google map 以编程方式选择注释 [Swift]

iphone - iPhone 上的 Twitter OAuth 登录页面

ios - 如何在 iOS 应用程序中处理自动旋转,其中一个 View 不应自动旋转,而一个 View 应该自动旋转?

iphone - 探索用于逆向工程目的的应用程序文件

xcode - Swift、Modal Segue 和 ViewController 问题

ios - SwiftUI View 和 UIKit View 的 z-index

ios - 类型 'Any?' 的值没有成员 'tag'

ios - 如何将表格内容移动到屏幕顶部?

ios - UIButton 不改变图像

html - 在 UITextView 中显示 HTML 文本崩溃发生在 swift 4 中?