I set up a UIButton in my Scene/View and the Button shows when the Scene is called by the ViewController. The problem is when I click the Button and my GameScene will be called, the Button will is still there. I think I set up the button in a wrong way.
I guess the problem is that I can't call the removeFromSuperview()
function on the button1 in my startGame
function.
How can I fix this? Any help is appreciated!
import Foundation
import SpriteKit
import UIKit
class MenuScene: SKScene {
override init(size: CGSize) {
super.init(size: size)
backgroundColor = SKColor.grayColor()
let label = SKLabelNode(fontNamed: "CourierNewPS-BoldMT")
label.text = "Start Game"
label.fontSize = 40
label.fontColor = SKColor.blackColor()
label.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(label)
}
override func didMoveToView(view: SKView) {
let button1=UIButton(frame: CGRectMake(size.width/2, size.height/2, 300, 100))
button1.backgroundColor = UIColor.greenColor()
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.setTitle("Unfocused", forState: .Normal)
button1.setTitle("Start", forState: .Focused)
button1.addTarget(self, action: "startGame:", forControlEvents: UIControlEvents.PrimaryActionTriggered)
self.view?.addSubview(button1)
}
func startGame(sender:UIButton) {
let gameView = view! as SKView
gameView.ignoresSiblingOrder = true
let reveal = SKTransition.flipHorizontalWithDuration(0.2)
let scene = GameScene(size: self.size)
gameView.presentScene(scene, transition:reveal)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
You have access to your button1
object with sender
from startGame(sender:UIButton)
method. It is the reference to button1
in this case. And you can call removeFromSuperview
method from it:
func startGame(sender:UIButton) {
let gameView = view! as SKView
gameView.ignoresSiblingOrder = true
let reveal = SKTransition.flipHorizontalWithDuration(0.2)
let scene = GameScene(size: self.size)
gameView.presentScene(scene, transition:reveal)
sender.removeFromSuperview()
}