Swift Spritekit 以编程方式添加按钮 [英] Swift Spritekit Adding Button programmatically

查看:36
本文介绍了Swift Spritekit 以编程方式添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式添加一个按钮,该按钮在被点击时会运行一个动作?将使用什么代码?

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

我习惯于在情节提要中添加一个按钮并从那里运行 IBAction.

I am used to just adding a button in the storyboard and running an IBAction from there.

推荐答案

在 SpriteKit 中添加按钮并响应点击它并不像在 UIKit 中那么容易.您基本上需要创建某种类型的 SKNode 来绘制您的按钮,然后检查您的场景中注册的触摸是否在该节点的范围内.

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!")
            }
        }
    }
}

如果您需要一个外观和动画与 UIKit 中的按钮相似的按钮,您需要自己实现;SpriteKit 没有内置任何内容.

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.

这篇关于Swift Spritekit 以编程方式添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆