Ele*_*ric 5 uiviewcontroller ios sprite-kit swift
我想了解从 GameScene 访问 UIViewController 方法的最佳实践是什么。现在我一直在使用 NSNotificationCenter,但由于我想要实现的特定功能,我不想使用它。
另外,如果没有任何其他方法可以通过 GameScene 访问 UIViewController,那么我真正想知道的是能够在没有 UIViewController 的情况下在 GameScene 中呈现 UIAlertController 的方法。
我只想为 UIViewController 创建一个全局变量,但我听说这是不好的做法。
谢谢!
您可以在 SKScenes 中显示 UIAlertController,只需在 rootViewController 上显示它们,这可能是显示它们的最佳位置。
self.view?.window?.rootViewController?.present...
Run Code Online (Sandbox Code Playgroud)
我不喜欢在 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)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在您的场景中,您需要显示警报,您只需遵守协议即可
class GameScene: SKScene, Alerts {
}
Run Code Online (Sandbox Code Playgroud)
并调用类似的方法
showAlert(title: "Alert title", message: "Alert message")
Run Code Online (Sandbox Code Playgroud)
就好像它们是场景本身的一部分一样。
享受
| 归档时间: |
|
| 查看次数: |
1690 次 |
| 最近记录: |