Swift Spritekit Adding Button programmatically

后端 未结 5 684
独厮守ぢ
独厮守ぢ 2020-12-01 11:46

How do I programmatically add a button that will run an action when it\'s clicked? What code would be used?

I am used to just adding a button in the storyboard and r

5条回答
  •  误落风尘
    2020-12-01 12:12

    Mike S - Answer updated for - Swift 5.2

    override func didMove(to view: SKView) {
            createButton()
            
        }
    
    func createButton()
        {
            // Create a simple red rectangle that's 100x44
            button = SKSpriteNode(color: SKColor.red, size: CGSize(width: 100, height: 44))
            // Put it in the center of the scene
            button.position = CGPoint(x:self.frame.midX, y:self.frame.midY);
            
            self.addChild(button)
            
        }
        
        override func touchesEnded(_ touches: Set, with event: UIEvent?) {
            let touch = touches.first
            let touchLocation = touch!.location(in: self)
                // Check if the location of the touch is within the button's bounds
                if button.contains(touchLocation) {
                    print("tapped!")
                }
            
        }
    

提交回复
热议问题