有很多方法可以处理这种情况,我不推荐 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,让其发送消息;
在视图控制器中
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)
另一种方法是使视图控制器全局化。
在视图控制器代码中:
私有变量_instance:UIViewController
class ViewController : UIViewController
{
class var instance
{
get
{
return _instance;
}
}
func viewDidLoad()
{
_instance = self;
}
}
然后只需调用
ViewController.instance!.
每当您需要访问视图控制器时。
这些方法都有其优点和缺点,因此请选择最适合您的方法。