swift - 当玩家再次玩游戏时,如何修复 SpriteKit Swift 上的分享按钮 Share Button 出现在游戏场景中?

标签 swift sprite-kit

这是我的“分享”按钮的代码:

ShareButton = UIButton(frame: CGRect(x: 0, y:0, width: view.frame.size.width / 3, height: 60))

ShareButton.center = CGPointMake(CGRectGetMidX(self.frame), 3*CGRectGetHeight(self.frame)/4)

ShareButton.setTitle("Share", forState: UIControlState.Normal)
ShareButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
ShareButton.addTarget(self, action: ("pressed:"), forControlEvents: .TouchUpInside)

self.view?.addSubview(ShareButton) 

PS:“我的分享”按钮可以使用,但当用户分享他的分数并想再次玩游戏时,“分享”按钮会出现在游戏场景中。

最佳答案

制作 SpriteKit 游戏的第一条规则是尽量不使用 UIKit。 您的所有 UI 都应该使用 SpriteKit API(SKLabelNodes、SKSpriteNodes、SKNodes 等)直接在 SKScenes 中创建。 这也有异常(exception),比如可能使用 UICollectionViews 来实现大量级别的选择菜单,但是基本的 UI 永远不应该使用 UIKit 来完成。

所以你应该使用 SKSpriteNodes 制作你的按钮,并将它们直接添加到你想要的 SKScene 中。

Google 上有很多关于如何做到这一点的教程,一个简单的就是这个

https://nathandemick.com/2014/09/buttons-sprite-kit-using-swift/

要获得更完整的游戏,请查看 apples 示例游戏“DemoBots”或查看 gitHub 上的这些很酷的项目。

https://github.com/nguyenpham/sgbutton

https://github.com/jozemite/JKButtonNode

在 SpriteKit 游戏中,您往往只有 1 个 View Controller (GameViewController),它将呈现您所有的 SKScenes(GameScene、MenuScene 等)。如果你使用 UIKit 元素,它们会被添加到 GameViewController 中,因此它们将显示在所有场景中(比如你的分享按钮)。

self.view?.addSubview(shareButton) // self.view is your GameViewController

如果您的游戏有超过 1 个 SKScene 和相当多的按钮,这将是难以管理的。

另一方面,如果您使用 SpriteKit API,并且因为每个 SKScene 在您进入时都以干净的状态启动,您不必担心这些。

如果您坚持使用 UIKit,则必须在转换到游戏场景之前删除或隐藏分享按钮,并在需要时取消隐藏或再次添加它。

 shareButton.isHidden = true

 shareButton.removeFromSuperview()

最后,作为良好做法,您的属性应该以小写字母而不是大写字母开头

shareButton = ...

希望对你有帮助

关于swift - 当玩家再次玩游戏时,如何修复 SpriteKit Swift 上的分享按钮 Share Button 出现在游戏场景中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432232/

相关文章:

swift - 如何在启动 OSX spritekit 应用程序时设置自定义光标?

ios - 设置自定义数据集值 - 图表 3.0.4 和使用 Swift 4.0

memory-leaks - 在 GameplayKit 中使用 GKStateMachine 的泄漏

ios - 在 SpriteKit 游戏中制作 Facebook 帖子

使用 AnyObject 的 Swift 协议(protocol)属性 - 无法从 Objective-C 桥接数组

swift - 无法将 child 添加到 GameScene,只能添加到 SKSpriteNode

swift - 在 SpriteKit 中显示 Game Center 排行榜

ios - 来自 Apple 网站的日期示例代码不起作用?

swift - 在 NavigationBar 中嵌入 NavigationButton

json - 从 NSURLConnection 加载 UITableView 时数据加载时间过长