LoginSignup
0

More than 5 years have passed since last update.

SpriteKitのGameSceneでUIViewControllerを操作する。

Posted at

Q.

SpriteKitのGameScene内でUIViewController使いたいんだけど

.presentとかでUIViewを表示したい時って結構あるはず
今回はMFMailComposeViewController(メール作成画面)を出そうとして結構苦労したのでメモ

A.

rootViewControllerを使おう

let currentViewController : UIViewController? = UIApplication.shared.keyWindow?.rootViewController!

現在の画面がcurrentViewController(変数名は任意)としてUIViewController?型で定義されるので.present使えるようになる

つまりUIViewが表示できるようになる

例) メール作成画面を開く

import SpriteKit
import GameplayKit
import MessageUI

class GameScene: SKScene , UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if dont_touch_display {
            return
        }
        sendmail()

    //-- ここからメール送信--//
    var mailViewController = MFMailComposeViewController()
    let currentViewController : UIViewController? = UIApplication.shared.keyWindow?.rootViewController!

    @IBAction func sendMail() {
        //メールを送信できるかチェック
        if MFMailComposeViewController.canSendMail()==false {
            print("Email Send Failed")
            return
        }

        let mailViewController = MFMailComposeViewController()
        let toRecipients = ["XXXX@gmail.sampledomainX"]

        mailViewController.mailComposeDelegate = self
        mailViewController.setSubject("メールの件名")
        mailViewController.setToRecipients(toRecipients) //Toアドレスの表示
        mailViewController.setMessageBody("メールの本文", isHTML: false)
        currentViewController?.present(mailViewController, animated: true, completion: nil)
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {

        if result == MFMailComposeResult.cancelled {
            print("メール送信がキャンセルされました")
        } else if result == MFMailComposeResult.saved {
            print("下書きとして保存されました")
        } else if result == MFMailComposeResult.sent {
            print("メール送信に成功しました")
        } else if result == MFMailComposeResult.failed {
            print("メール送信に失敗しました")
        }
        currentViewController?.dismiss(animated: true, completion: nil) //閉じる

    }

参考リンク

http://www.swift-study.com/mfmailcomposeviewcontroller-basic/
https://stackoverflow.com/questions/37366763/how-can-i-dismiss-a-viewcontroller-from-my-gamescene-swift

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
0