gpt4 book ai didi

swift - 如何在 SKScene 中正确设置 UIButton

转载 作者:行者123 更新时间:2023-11-30 10:09:46 25 4
gpt4 key购买 nike

我在场景/ View 中设置了一个 UIButton,当 ViewController 调用场景时,该按钮就会显示。问题是当我单击按钮并且我的游戏场景将被调用时,按钮仍然存在。我认为我以错误的方式设置了按钮。
我想问题是我无法在 startGame 函数中的 button1 上调用 removeFromSuperview() 函数。

我该如何解决这个问题?如有任何帮助,我们将不胜感激!

import Foundation
import SpriteKit
import UIKit

class MenuScene: SKScene {


override init(size: CGSize) {

super.init(size: size)

backgroundColor = SKColor.grayColor()

let label = SKLabelNode(fontNamed: "CourierNewPS-BoldMT")
label.text = "Start Game"
label.fontSize = 40
label.fontColor = SKColor.blackColor()
label.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(label)
}


override func didMoveToView(view: SKView) {

let button1=UIButton(frame: CGRectMake(size.width/2, size.height/2, 300, 100))
button1.backgroundColor = UIColor.greenColor()
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.setTitle("Unfocused", forState: .Normal)
button1.setTitle("Start", forState: .Focused)
button1.addTarget(self, action: "startGame:", forControlEvents: UIControlEvents.PrimaryActionTriggered)

self.view?.addSubview(button1)
}



func startGame(sender:UIButton) {
let gameView = view! as SKView
gameView.ignoresSiblingOrder = true

let reveal = SKTransition.flipHorizontalWithDuration(0.2)
let scene = GameScene(size: self.size)
gameView.presentScene(scene, transition:reveal)

}


required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

最佳答案

您可以通过 startGame(sender:UIButton) 方法中的 sender 访问您的 button1 对象。在本例中,它是对 button1 的引用。您可以从中调用 removeFromSuperview 方法:

func startGame(sender:UIButton) {
let gameView = view! as SKView
gameView.ignoresSiblingOrder = true

let reveal = SKTransition.flipHorizontalWithDuration(0.2)
let scene = GameScene(size: self.size)
gameView.presentScene(scene, transition:reveal)

sender.removeFromSuperview()
}

关于swift - 如何在 SKScene 中正确设置 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33615060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com