简体   繁体   English

Swift:在ViewController中访问变量

[英]Swift : Access variable in ViewController

I have a View Controller with a button, an index, and a function thats called when the button is pressed, here is an example of the code: 我有一个带有按钮,索引和一个按下按钮时调用的函数的View Controller,这是代码示例:

View Controller: 视图控制器:

func buttonPressed(){

index++

}

Then i have a class in which i want to access and print the index from the View Controller 然后我有一个我想在其中访问并从View Controller打印索引的类

Class: 类:

print("Index is \(ViewController().index)")

Obviously this doesn't work, does anyone know how I can access this? 显然这是行不通的,有人知道我该如何访问吗? I can't really instantiate it because its a ViewController as well as it will not be the same index.I think. 我无法真正实例化它,因为它的ViewController以及它都不是相同的索引。

You can save your index to NSUserDefaults or to a plist file. 您可以将索引保存到NSUserDefaults或plist文件。 Try using a getter and a setter to make it persist automatically as follow: 尝试使用getter和setter使它自动持久化,如下所示:

Xcode 8.3.3 • Swift 3.1.1 Xcode 8.3.3•Swift 3.1.1

extension UserDefaults {
    var indexA: Int {
        get {
            return integer(forKey: "indexA")
        }
        set {
            set(newValue, forKey: "indexA")
        }
    }
}

usage: 用法:

To load it 加载

let indexA = UserDefaults.standard.indexA

To set/change it 设置/更改

UserDefaults.standard.indexA = 10

You should: 你应该:

  1. Add set public or internal modifier for index in order to use it outside a class index添加集合public或internal修饰符,以便在类外使用

  2. Create an instance of ViewController 创建一个ViewController的实例

  3. Retrieve index from an instance 从实例检索index

     let vc = ViewController() print("index: \\(vc.index)") 
let vc = ViewController()  
print("index: \(vc.index)")

is not correct because vc in there is not viewController,that contain button you clicked. 不正确,因为vc中没有viewController,其中包含您单击的按钮。 It has to be declared again 必须再次声明

In case, you should have a singleton of ViewController(ex: viewcontrollerInstall ) and put in anywhere so you can access In ViewDidLoad of ViewController you set viewcontrollerInstall = self 以防万一,您应该拥有一个ViewController单例(例如: viewcontrollerInstall ),并放置在任何地方,以便可以访问在ViewController ViewDidLoad ,您可以设置viewcontrollerInstall = self

And in your new class call : 在您的新课堂电话中:

print("Index is \(viewcontrollerInstall.index)")

Try passing the reference of the view controller which has the index and button to the class where you want to access it. 尝试将具有索引和按钮的视图控制器的引用传递给要访问它的类。

From there on you can access the same index value and other properties of that view controller in that class. 从那里,您可以访问该类中该视图控制器的相同索引值和其他属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM