Swift:如何从View控制器访问AppDelegate变量? [英] Swift: How to access in AppDelegate variable from the View controller?

查看:210
本文介绍了Swift:如何从View控制器访问AppDelegate变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文本或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:

快速1-2语法

var theViewController = ViewController()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.myViewController = theViewController

快速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的viewcontroller来访问数据,只需访问其属性即可:

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:如何从View控制器访问AppDelegate变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆