我想将视图控制器中的变量写入文本或csv(首选)文件。
事实上,我正在制作一个绘图应用程序,并希望将手指的当前位置写入文件中。
class ViewController: UIViewController {var lastPoint = CGPoint.zeroPoint ... }
我想从AppDelegate中访问lastPoint.x和lastPoint.y,我该如何做?谢谢。
我想将视图控制器中的变量写入文本或csv(首选)文件。
事实上,我正在制作一个绘图应用程序,并希望将手指的当前位置写入文件中。
class ViewController: UIViewController {var lastPoint = CGPoint.zeroPoint ... }
我想从AppDelegate中访问lastPoint.x和lastPoint.y,我该如何做?谢谢。
你的问题有些混乱,但如果这就是你要找的:
你可以通过获取对其的引用来访问appDelegate,如下所示:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
之后,如果你在你的appDelegate中存储了一个名为lastPoint的属性,你可以非常简单地访问它的组件,就像这样:
let x = appDelegate.lastPoint.x
let y = appDelegate.lastPoint.y
如果你需要从AppDelegate访问你的viewController属性,那么我建议在你的appdelegate中引用你的视图控制器:
var myViewController: ViewController!
当你的视图控制器被创建时,你可以将其引用存储在appdelegate属性中:
如果你在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 中创建了您的视图控制器:
self.myViewController = ViewController()
之后,您可以通过访问其属性从appdelegate中的viewcontroller访问数据,就像这样:
let x = self.myViewController.lastPoint.x
let y = self.myViewController.lastPoint.y
Swift 3 更新
var theViewController = ViewController()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.myViewController = theViewController
class BaseViewController {
lazy var appDelegate : AppDelegate {
return UIApplication.shared.delegate as? AppDelegate
}
}
使用BaseViewController继承其他视图控制器,并通过此方式访问
class ViewController : BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(self.appDelegate?.lastPoint.x)
print(self.appDelegate?.lastPoint.x)
}}
我成功地通过在AppDelegate.swift中创建ViewController的实例来访问我的ViewController,例如:
var mainViewController = ViewController()
func applicationWillEnterForeground(_ application: UIApplication) {
mainViewController.myVariable = "Hello".
}
然而,我不明白AppDelegate是如何“知道”mainViewController应该指向那个特定的ViewController。虽然我的应用只有一个视图和一个ViewController,这很好,但如果我有多个与不同UIView关联的ViewControllers呢?希望这里的任何人都能为此提供一些启示。 最好的问候, 安德烈