Swift:如何从视图控制器访问 AppDelegate 变量? [英] Swift: How to access in AppDelegate variable from the View controller?
问题描述
我想在文本或 csv(首选)文件中写入视图控制器中的变量.
I would like to write in the text or csv (prefer) file the variable from the view controller.
事实上,我正在做一个绘图应用程序,我想在文件中写入手指的当前位置.
Indeed I am doing a drawing app and I would like to write in the file the current position of the finger.
class ViewController: UIViewController {var lastPoint = CGPoint.zeroPoint ... }
我想从 AppDelegate 访问 lastPoint.x 和 lastPoint.y.我怎么能那样做?谢谢.
I would like to have access to lastPoint.x and lastPoint.y from the AppDelegate. how I could do that ? Thank you.
推荐答案
你的问题充满了困惑,但如果这就是你要找的:
Your question is full of confusion but if that's what you are looking for:
您可以通过获取对 appDelegate 的引用来访问它:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
之后,如果您在 appDelegate 中存储了一个名为 lastPoint 的属性,您就可以非常简单地访问它的组件:
after that if you have store a property called lastPoint in your appDelegate you can access its components very simply like that:
let x = appDelegate.lastPoint.x
let y = appDelegate.lastPoint.y
如果您需要从 AppDelegate 访问您的 viewController 属性,那么我建议在您的 appdelegate 中引用您的视图控制器:
var myViewController: ViewController!
然后当你的视图控制器被创建时,你可以在 appdelegate 属性中存储对它的引用:
then when your view controller is created you can store a reference to it in the appdelegate property:
如果您在 appDelegate 之外创建视图控制器:
If your create your view controller outside of your appDelegate:
Swift 1-2 语法
var theViewController = ViewController()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.myViewController = theViewController
Swift 3-4 语法
var theViewController = ViewController()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.myViewController = theViewController
如果您在 appDelegate 内创建视图控制器:
If you create your view controller inside of your appDelegate:
self.myViewController = ViewController()
之后,您只需像这样访问它的属性,就可以从您的 appdelegate 从您的视图控制器访问您的数据:
After that you can access your data from your viewcontroller from your appdelegate just by accessing its property like that:
let x = self.myViewController.lastPoint.x
let y = self.myViewController.lastPoint.y
这篇关于Swift:如何从视图控制器访问 AppDelegate 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!