Swift : Access variable in ViewController

跟風遠走 提交于 2019-12-20 07:38:37

问题


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:

func buttonPressed(){

index++

}

Then i have a class in which i want to access and print the index from the 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.


回答1:


You can save your index to NSUserDefaults or to a plist file. Try using a getter and a setter to make it persist automatically as follow:

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



回答2:


You should:

  1. Add set public or internal modifier for index in order to use it outside a class

  2. Create an instance of ViewController

  3. Retrieve index from an instance

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



回答3:


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

is not correct because vc in there is not viewController,that contain button you clicked. 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

And in your new class call :

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



回答4:


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.



来源:https://stackoverflow.com/questions/35078674/swift-access-variable-in-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!