在swift中显示UIAlertView的简单方法是:
let alert = UIAlertView() alert.title = "Alert!" alert.message = "A wise message" alert.addButtonWithTitle("Ok, thank you") alert.show()
但现在这在iOS 9中已经过折旧,建议使用UIAlertController
:
let myAlert: UIAlertController = UIAlertController(title: "Alert!", message: "Oh! Fancy", preferredStyle: .Alert) myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(myAlert, animated: true, completion: nil)
哪个好,但我在使用SpriteKit并在GameScene中,这给出了一个错误Value of type 'GameScene' has no member 'presentViewController'
...
我是否需要切换回我的ViewController来呈现这个或者有没有办法从GameScene中调用它.
我找到了这个答案,但它是Objective-C.
有很多方法可以处理这种情况,我不建议使用Jozemite Apps答案,因为这会导致有超过1个视图控制器的应用程序出现问题.(您希望在当前视图控制器上显示警报,而不是根目录)
我这样做的首选方式是通过授权.需要做的是创建一个处理消息传递的协议:
import Foundation protocol ViewControllerDelegate { func sendMessage(message:String); }
在您的视图控制器中:
class ViewController : UIViewController, ViewControllerDelegate { ... func sendMessage(message:String) { //do alert view code here } //in the view controllers view did load event func viewDidLoad() { var view = self.view as! GameSceneView view.delegate = self }
在您的视图代码中:
var delegate : ViewControllerDelegate
最后在你想要呈现的游戏场景中:
self.view.delegate?.sendMessage(message)
这种方式允许对VC的有限访问,并且可以在需要时使用更多选项进行修改.
另一种方法是建立一个通知系统,并使用NSNotificationCenter将消息从场景传递给当前VC并让它发送消息;
在ViewController中
func viewDidLoad() { NSNotificationCenter.defaultCenter().addObserver(self,selector:"AlertMessage:",name:"AlertMessage",object:nil); } func AlertMessage(notification:NSNotification) { if(let userInfo = notification.userInfo) { let message = userInfo["message"] ....//do alert view call here } }
在游戏场景代码中:
...at the spot you want to send a message let userInfo = ["message":message]; NSNotificationCenter.defaultCenter.postNotificationNamed("AlertMessage",object:nil,userInfo:userInfo)
另一种方法是将视图控制器指针保存到游戏场景视图:
//in Game Scene View code var viewController : UIViewController; //in the view controllers view did load event func viewDidLoad() { var view = self.view as! GameSceneView view.viewController = self } //finally in game scene where you want to present let myAlert: UIAlertController = UIAlertController(title: "Alert!", message: "Oh! Fancy", preferredStyle: .Alert) myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.view.viewController.presentViewController(myAlert, animated: true, completion: nil)
另一种方法是使视图控制器全局化.
在视图控制器代码中:private var _instance:UIViewController
class ViewController : UIViewController { class var instance { get { return _instance; } } func viewDidLoad() { _instance = self; } }
然后打电话
ViewController.instance!.
每当您需要访问视图控制器时.
这些方法中的每一种都有优点和缺点,因此请选择最适合您的方法.