注意:
已经有几个与此相关的问题(或资源):
Present an UIAlertController with a SpriteKit scene (Objective-C)
Displaying a UIAlertController in GameScene (SpriteKit/Swift)
所以我很抱歉添加了类似的问题。但是,我尝试实现这些解决方案,但没有成功。
为了使这个问题比前面提到的问题更具体一些,让我们使用 M.W.E. ( Stack Overflow SKSpriteKit ) 在另外两个 Swift 相关问题中提出:
- Swift: SKSpriteKit, using Storyboards, UIViewController and UIButton to set in game parameters?
- Swift: returning to Main Menu after condition is met in GameScene using StoryBoards and UIViewControllers?
上下文:
在 M.W.E.
主要有一个UIViewController
, GameViewController
调用主菜单场景,即 SKView
。各种定制SKView
s 循环链接:
菜单 -> 难度 -> 游戏 -> 得分 -> 菜单 -> 等等
我提到这一点,是因为在上述大多数问题中,必须添加 UIAlertController
转到主UIViewController
。我只是想确保只有 GameScene
可以呈现UIAlertController
没有其他场景。
问题:
我如何实现UIAlertController
只能从 SKView
之一调用是?之前的一些答案,只有主要的GameViewController
和GameScene
,然后给出GameScene
( GameViewController
中的常量)对 GameViewController
的引用。由于在此代码中,GameScene
直到很久以后才被访问,如何实现这一点(理想情况下不通过各种 GameViewController
传播对 SKView
的引用。
请使用 M.W.E.回答这个问题的时候。
目标:
在另一个相关问题中,
Swift3: UISwipeGestureRecognizer in only one of putatively many SKViews ,它提出了如何实现UIGestureRecognizer
一个SKView
。理想情况下,UIAlertController
将在该操作之后呈现 - 作为游戏中的菜单。
最小工作示例
最佳答案
UIAlert
是一个 UIKit
元素,因此您可以轻松地在 SKScene
中呈现您想要的位置,只需很少的代码即可从您的 View 中获取引用..
换句话说,您可以访问显示应用内容的主窗口
,然后使用提供窗口内容 View 的rootViewController
。
代码示例:
if sprite.contains(touchLocation) {
print("You tapped the blue sprite")
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
alert.addAction(action)
if let vc = self.scene?.view?.window?.rootViewController {
vc.present(alert, animated: true, completion: nil)
}
}
关于 swift 3 : adding a UIAlertController in a SKView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823096/