Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

Swift Spritekit Adding Button programmatically

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 running an IBAction from there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding a button in SpriteKit and responding to taps on it is not quite as easy as it is in UIKit. You basically need to create an SKNode of some sort which will draw your button and then check to see if touches registered in your scene are within that node's bounds.

A really simple scene with just a single red rectangle in the center acting as a button would look something like this:

import UIKit
import SpriteKit
class ButtonTestScene: SKScene {
    var button: SKNode! = nil
    override func didMove(to view: SKView) {
        // Create a simple red rectangle that's 100x44
        button = SKSpriteNode(color: .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<UITouch>, with event: UIEvent?) {
        // Loop over all the touches in this event
        for touch in touches {
            // Get the location of the touch in this scene
            let location = touch.location(in: self)
            // Check if the location of the touch is within the button's bounds
            if button.contains(location) {
                print("tapped!")
            }
        }
    }
}

If you need a button that looks and animates like the ones in UIKit, you'll need to implement that yourself; there's nothing built in to SpriteKit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...