John_Sm1 John_Sm1 - 1 month ago 10x
Swift Question

Swift & SpriteKit - How to present alert view in GameScene

I need help presenting an alert view in the game scene. Im currently struggling to do so as GameScene.Swift isnt a standard ViewController. If it helps I need to do so as I need the user to input a value which is used as a coordinate for the ball Sprite Kit Node in my game. The input is only a standard integer so that isnt an issue. Any other idea of how I can do this which isnt through an alert view is also welcome.

override func viewWillLayoutSubviews() {

let view = self.view as! SKView

if view.scene == nil {

view.showsFPS = false
view.showsNodeCount = false

let gameScene = GameScene(size: view.bounds.size)
gameScene.scaleMode = SKSceneScaleMode.AspectFill


That is in the GameViewController file

var vc : GameViewController!

override init(size: CGSize) {
super.init(size: size)

let alertController = UIAlertController(title: "Bll Starting Position", message: "Please Enter a X Coordinate Value IN Range 0 to 345 ", preferredStyle: .Alert)
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Value Must Be In Range 0 To 345"
textField.autocapitalizationType = UITextAutocapitalizationType.None
textField.autocorrectionType = UITextAutocorrectionType.No
textField.clearsOnBeginEditing = true
textField.clearsOnInsertion = true
textField.clearButtonMode = UITextFieldViewMode.Always
let cancelBtn = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
let confirmBtn = UIAlertAction(title: "Confirm", style: .Default, handler: { (confirmView) in
if let field = alertController.textFields![0] as? UITextField {

alertController.addAction(cancelBtn), animated: true, completion: nil)




There may be the following options:

1) Quick solution. Do not use UIAlertController, use UIAlertView. Like that:

However, UIAlertView is deprecated so it's not quite safe to rely on it.

2) A better solution. Make your SKScene subclass hold a reference to the view controller which you use to present the scene and when you create the scene assign it the view controller:

myScene.viewController = self

And then you can use it.

self.viewController.presentViewController(alertController, animated: true, completion: nil)