我正在尝试为一个游戏设置缩放,在这个游戏中,单击一个按钮可以放大,另一个按钮可以缩小(这将是用户界面的一部分)。
我无法将按钮输入到代码中。我能读到按钮没有按下,但如果按下它我就不知道怎么读。
通过查看API引用,我想到尝试使用按钮的“state”,但它总是返回0,即使按钮被按下。这可能是因为更新函数的更新速度不如按钮状态的更改快。
这是我的代码:

class GameScene: SKScene {
    override func sceneDidLoad() {
        cam = SKCameraNode()
        cam.xScale = 1
        cam.yScale = 1
        self.camera = cam
        self.addChild(cam)
        cam.position = CGPoint(x: 0, y: 0)
        setUpUI()
    }

    func setUpUI(){
        let button1Rect = CGRect(x: 20, y: 80, width: 80, height: 40)
        let zoomIn = NSButton(frame: button1Rect) //place a button in the Rect
        zoomIn.setButtonType(NSMomentaryPushInButton)
        zoomIn.title = "Zoom In"
        zoomIn.alternateTitle = "Zoom In"
        zoomIn.acceptsTouchEvents = true
        view?.addSubview(zoomIn) //put button on screen
        let button2Rect = CGRect(x: 20, y: 30, width: 80, height: 40)
        let zoomOut = NSButton(frame: button2Rect) //place a button in the Rect
        zoomOut.setButtonType(NSMomentaryPushInButton)
        zoomOut.title = "Zoom Out"
        zoomOut.alternateTitle = "Zoom Out"
        zoomOut.acceptsTouchEvents = true
        view?.addSubview(zoomOut) //put button on screen
        if zoomIn.state == 1{ //this loop is never true no matter how many times I press the button
            print("zoom")
        }
    }
}

我确实删掉了一些涉及鼠标的代码,因为它与此无关。

最佳答案

答案来自ValyreanGroup。
只需在setUpUI()函数外定义按钮(在游戏场景外或在其工作范围内,在游戏场景外更容易)。

关于swift - 如何在Swift MacOS中获得按钮 Action ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42563883/

10-12 00:21
查看更多