Search code examples
iosswiftbuttonviewcontrollerxcode-storyboard

Making a button not hidden in GameScene


Hello my question is simply how to unhide a button in GameScene. I have a segueToMainMenu button that is set up in storyboard. This is how my GameViewController looks:

@IBOutlet weak var segueToMainMenu: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    let scene = GameScene(size: view.bounds.size)
    let skView = view as! SKView
    skView.showsFPS = true
    skView.showsNodeCount = true
    skView.ignoresSiblingOrder = false
    scene.scaleMode = .AspectFill
    skView.presentScene(GameScene(size: skView.bounds.size))
    scene.viewController = self

    self.segueToMainMenu.hidden = true
}

I set the button to hidden but now in my game I would like to unhide it when a lose func runs in GameScene since when the button is clicked it segues back to the main menu which is a separate view controller also created in the storyboard. Anything helps thank you.


Solution

  • You either can create a delegate for you scene which will call appropriate method on gameOver and do something like

    // in the view controller
    func gameSceneDidSendGameOver() {
        self.segueToMainMenu.hidden = false
    }
    
    //in the scene
    var gameOverDelegate : GameOverDelegate?
    
    func gameOver() {
        gamOverDelegate?.gameSceneDidSendGameOver()
    }
    

    Or do it a little bit of ugly way like:

    func gameOver() {
        let gvc = self.viewController as GameViewController
        gvc.segueToMainMenu.hidden = false
    }
    

    Edit: Declaration of the delegate protocol.

    protocol GameOverDelegate {
        func gameSceneDidSendGameOver()
    }
    
    class GameViewController : ViewController, GameOverDelegate {
    ...
        func gameSceneDidSendGameOver() {
            self.segueToMainMenu.hidden = false
        }
    }