[Swift] SpriteKit SKSceneからpresentViewControllerを使う方法

2015/07/30
SpriteKitから、presentViewControllerを使用することは通常では難しいようだ。
理由はSKSceneが、UIViewControllerを既に継承しているらしく、
多重継承になってしまうかららしい。
(既に継承しているはずなのに、使えないのはどういうことなのか詳しくは私には謎・・・)

まあそのせいで、SpriteKitから、
presentViewControllerを呼び出すのが難しく、そのせいで
ダイアログを出したり、ツイッターやFacebookを使ったりするのが簡単にはいかなくなるようだ。

ネットで色々調べると、presentViewControllerを使用せずに使う方法を模索している情報が多いが、
そんな
中、最もシンプルなやり方をとっている情報があったので書き留めたい。

SKSceneと言えど、Viewの最も最前面にはUIViewContollerが存在しており、
それを取得してきて、そこから使用するというもの。


var currentViewController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController!
currentViewController?.presentViewController(・・・・・・・)



これだけで取得できる。
すごい。


たとえばダイアログなら、以下のようにすぐに使用できる。

let alertController0 = UIAlertController(title: "確認", message: "すべてのデータを初期化しますか?", preferredStyle: .Alert)
let otherAction0 = UIAlertAction(title: "Yes", style: .Default) {
    action in println("初期化しました")
}
let cancelAction0 = UIAlertAction(title: "No", style: .Cancel) {
action in println("やめました")
}
alertController0.addAction(otherAction0)
alertController0.addAction(cancelAction0)

var currentViewController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController!
currentViewController?.presentViewController(alertController0, animated: true, completion: nil)
関連記事
comment (0) @ tips
今作っているゲームがようやくひと区切り | [Swift] シーン変更によるクラスの持続と破棄・インスタンスの持続と破棄

comment

コメントを送る。

URL:
Comment:
Pass:
Secret: 管理者にだけ表示を許可する