您可以在 SKScenes 中显示 UIAlertController,只需在 rootViewController 上显示它们,这可能是显示它们的最佳位置。
self.view?.window?.rootViewController?.present...
我不喜欢在 SKScenes 中引用 GameViewController,而且我实际上从未达到被迫这样做的地步。 NSNotificationCenter、委托或协议扩展是更好的方法。
实际上,我使用 Swift 2 协议扩展制作的警报助手,因为我喜欢干净、可重用且尽可能少的重复代码。
只需创建一个新的 .swift 文件并添加此代码
import SpriteKit
protocol Alerts { }
extension Alerts where Self: SKScene {
func showAlert(title title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ in }
alertController.addAction(okAction)
self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
func showAlertWithSettings(title title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ in }
alertController.addAction(okAction)
let settingsAction = UIAlertAction(title: "Settings", style: .Default) { _ in
if let url = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.sharedApplication().openURL(url)
}
}
alertController.addAction(settingsAction)
self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
现在,在您的场景中,您需要显示警报,您只需遵守协议即可
class GameScene: SKScene, Alerts {
}
并调用类似的方法
showAlert(title: "Alert title", message: "Alert message")
就好像它们是场景本身的一部分一样。
Enjoy