I programmed an SKButton class. The problem is that the button doesn't show up in my scene even though I added it to this one. I also programmed a joystick, but it is displayed. What did I do wrong?
SKButton:
import SpriteKit
class SKButton: SKNode {
let background: SKSpriteNode = SKSpriteNode(color: UIColor.red, size: CGSize(width: 100, height: 10))
let text: SKLabelNode = SKLabelNode()
var buttonText: String = ""
var backgroundColor: UIColor = UIColor.red
var fontSize: CGFloat = 0.0
var fontName: String = ""
var fontColor: UIColor = UIColor.white
var buttonAction: (() -> ())?
init(text: String, backgroundColor: UIColor, fontName: String, fontSize: CGFloat, fontColor: UIColor) {
super.init()
buttonText = text
self.backgroundColor = backgroundColor
self.fontName = fontName
self.fontSize = fontSize
self.fontColor = fontColor
initialize()
addChild(background)
addChild(self.text)
print("init")
}
func tapped(touch: UITouch) {
let node: SKNode = atPoint(touch.location(in: self))
if let name = node.name {
if name == "B" || name == "T" {
if let buttonAction = buttonAction {
buttonAction()
print("tapped")
}
}
}
}
func initialize() {
text.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center
text.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
text.fontSize = fontSize
text.fontColor = fontColor
text.fontName = fontName
text.text? = buttonText
text.position = CGPoint.zero
text.zPosition = 1
text.name = "T"
background.zPosition = 0
background.position = CGPoint.zero
background.size = CGSize(width: text.frame.width * 1.25, height: text.frame.height * 1.5)
background.color = backgroundColor
background.name = "B"
print("initialize")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I checked YouTube and StackOverflow, but couldn't find an answer. If there is, I have overlooked it. But I've really tried hard to find an answer. That is why I am asking the question here.
I created a constant of my button in the scene:
let startButton: SKButton = SKButton(text: "START", backgroundColor: UIColor.red, fontName: "Arial", fontSize: 20, fontColor: UIColor.white)
Then I moved the button to the right place:
startButton.position = CGPoint(x: size.width / 2, y: size.height / 2 + startButton.background.size.height * 0.75)
And then I added it to my scene:
addChild(startButton)