swift - 以编程方式添加的 UIButton 在切换场景后不会消失

标签 swift uibutton skscene

我在 Swift 3 中使用游戏应用程序模板,当我从“开始”屏幕转换到“游戏”场景时,“开始”屏幕上的按钮不会消失。 我读过其他人的类似帖子,但没有任何帮助。我的按钮是一个以编程方式添加的 uibutton,按钮后面有一个 uibezierpath 圆角矩形,使其看起来不错。问题是,当我更改场景时,它(按钮和 UIBezierpath)不会消失 - 它与“开始”屏幕位于完全相同的位置。 我的按钮代码与 UIBezierpath:

let playAgain = UIButton()
        playAgain.frame = CGRect(x: 225, y: 247, width: 115, height: 36)

        playAgain.backgroundColor = SKColor.lightGray
        playAgain.setTitle("Play", for: .normal)

    playAgain.setTitleColor(.black, for: .normal)

        self.view?.addSubview(playAgain)
        playAgain.addTarget(self, action: #selector(playAgainTapped(_:)), for: .touchUpInside)
        //now for the bezierpath/ rounded rect
        //let doYourPath = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 100, height: 36))

        //this also works
        let roundRect = UIBezierPath(roundedRect: CGRect(x: 218, y: 240, width: 130, height: 50), cornerRadius: 18)
        let layer = CAShapeLayer()
        layer.path = roundRect.cgPath
        layer.strokeColor = UIColor.black.cgColor
        layer.fillColor = UIColor.lightGray.cgColor
        self.view?.layer.addSublayer(layer)

func playAgainTapped(_ sender: Any?) -> Void {
        print("***********")

        backToGame()
    }

切换场景代码:

func backToGame(){
        removeAllChildren()

        run(SKAction.sequence([
            SKAction.wait(forDuration: 3.0),
            SKAction.run() {
                // 5
                let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
                let scene = GameScene(size: self.size)
                self.view?.presentScene(scene, transition:reveal)
            }
            ]))
    }

有什么想法吗?

最佳答案

您正在与按钮的 super View 相同的 View 上呈现场景。

由于场景独立于场景中的 View ,因此您的按钮将保持不变,因此如果您希望删除该按钮,则应该显式删除该按钮。

全局声明按钮和圆角矩形,并从 backToGame 中的 super View / super 层删除它们

let playAgain = UIButton()
let layer = CAShapeLayer()

func backToGame(){
    removeAllChildren()

    playAgain.removeFromSuperview()
    layer.removeFromSuperlayer()

    run(SKAction.sequence([
        SKAction.wait(forDuration: 3.0),
        SKAction.run() {
            // 5
            let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
            let scene = GameScene(size: self.size)
            self.view?.presentScene(scene, transition:reveal)
        }
        ]))
}

关于swift - 以编程方式添加的 UIButton 在切换场景后不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45644504/

相关文章:

ios - 跨多个 SKScene 使用 SKEmitterNode

ios - UIPageControl 不适用于 voiceOver

ios - 快速转换时区之间的日期

swift - 改变触摸按钮的颜色......然后再回来

ios - 更改 UIButton 的标题不起作用

iOS Spritekit 滚动菜单

ios - 如何使用 UIGestureRecognizers 相对于触摸位置旋转 UIScrollView 内的 UIImageView

ios - 将字符串转换为 NSDate 给出错误的日期

ios - 折叠隐藏的 UIButton

swift - UILabel 没有出现在 SKScene 上