的确,我正在做一个绘图应用程序,我想在文件中写入手指的当前位置.
- class ViewController: UIViewController {var lastPoint = CGPoint.zeroPoint ... }
我想从AppDelegate访问lastPoint.x和lastPoint.y.我该怎么办?谢谢.
的确,我正在做一个绘图应用程序,我想在文件中写入手指的当前位置.
- 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语法
- 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