[英]How to get action of button in Swift MacOS
我正在尝试为游戏设置缩放,您可以单击某个按钮进行放大,而另一个则缩小(这将是UI的一部分)。
我在向代码输入按钮时遇到问题。 我可以读到没有按下按钮,但如果按下按钮,我无法弄清楚如何阅读。
通过API参考查看了我的想法,尝试使用按钮的“状态”,但它总是返回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")
}
}
}
我确实删除了一些涉及鼠标的代码,因为它不相关。
答案来自TheValyreanGroup。
只需在setUpUI()函数外部定义按钮(在GameScene之外或在其中工作,在GameScene之外更容易)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.