简体   繁体   中英

How to get action of button in Swift MacOS

I am trying to set up zoom for a game where you click on a button to zoom in, and another to zoom out (which will be part of the UI).

I am having problems getting the input of the buttons to the code. I can read that the button is not pressed, but I cannot figure out how to read if it is pressed.

Looking through the API reference gave me the idea to try using the "state" of the button, but it always returns 0, even when the button is pressed. This could be because the update function does not update as fast as the button's state changes.

Here is my code:

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

I did cut out some of the code involving the mouse as it is not relevant.

Answer is from TheValyreanGroup.

Simply define the button outside of the setUpUI() function (outside of the GameScene or within it works, outside of the GameScene is easier).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM