LoginSignup
8
8

More than 5 years have passed since last update.

Storyboardを使用せずに、SpriteKitを使用したゲームを作成する

Last updated at Posted at 2015-03-13

AppleはStoryboardの使用を推奨(Xcode6からEmpty Applicationテンプレートを削除)しているようですが、どうも仕様がブラックボックス化されている気がするので、削除してアプリを作成してみます。

類似記事:Gameテンプレートを使用せず、横向きゲームアプリを作成する

SingleViewApplicationからStoryboardを削除する

Empty Applicationテンプレートがないので、Single View Applicatinでプロジェクトを立ち上げます
template.png

Main.storyboardを削除(右クリック - Delete)し、Development InfoのMain Interfaceを空白にします(Mainを削除)

developmentinfo.png

AppDelegate、ViewControllerの修正

初回起動時に呼ばれるAppDelegateのapplicationメソッドで、ViewControllerを生成し、rootViewに設定します

AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        if let window = window{
            window.backgroundColor = UIColor.whiteColor()
            window.rootViewController = ViewController()
            window.makeKeyAndVisible()
        }
        return true
    }

続いて、ViewControllerでSKViewを生成します。ここでハマりました。
今まではStoryboardで、SKViewクラスを設定していましたが、それをどのように定義してよいかがわからなかったからです。

結論から言うと、viewDidLoadメソッドよりも先に呼ばれるloadviewメソッドをオーバライドして、self.viewをSKViewに差し替えてやると良いようです。
iOS Developer Library:UIKit Framework Reference UIViewController Class Reference

ViewController.swift
import UIKit
import SpriteKit

class ViewController: UIViewController {
    //var skView: SKView!
    var viewInitiated: Bool = false

    override func loadView() {
        let skView = SKView()
        self.view = skView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillLayoutSubviews() {
        if(!viewInitiated){
            super.viewWillLayoutSubviews()
            var skView = self.view as SKView
            skView.showsFPS = true

            skView.showsNodeCount = true
            let scene = GameScene(size: skView.bounds.size)

            skView.presentScene(scene)
            self.viewInitiated = true
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}
GameScene.swift
import SpriteKit

class GameScene: SKScene {
    var initiated: Bool = false

    override func didMoveToView(view: SKView) {
        if(!initiated){
            self.initContent()
            self.initiated = true
        }
    }
    func initContent(){
        self.backgroundColor = UIColor.redColor()
    }
}

これで真っ赤な背景を表示することができました。

iphone.png

参考

How do I create a new Swift project without using Storyboards?
さよならテンプレート

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8