Swift: access variable in ViewController

I have a View Controller with a button, index, and a function that is called when a button is clicked, here is a sample code:

View controller:

func buttonPressed(){ index++ } 

Then I have a class in which I want to access and print the index from View Viewer

Grade:

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

Obviously this does not work, does anyone know how I can access it? I cannot create an instance because its ViewController will also not be the same index. I think.

-1
source share
4 answers

You can save your index in NSUserDefaults or in a plist file. Try using a getter and setter so that it is saved automatically, as shown below:

Xcode 8.3.3 โ€ข Swift 3.1.1

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

using:

To download it

 let indexA = UserDefaults.standard.indexA 

To set / change it

 UserDefaults.standard.indexA = 10 
+3
source

You must:

  • Add a public or internal modifier for index to use it outside the class

  • Create an instance of ViewController

  • Extract index from instance

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

incorrect because vc does not have a viewController in it that has the button you clicked. It must be announced again

In case you need to have a singleton ViewController (ex: viewcontrollerInstall ) and placed anywhere so that you can access In ViewDidLoad of ViewController you set viewcontrollerInstall = self

And in your new class call:

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

Try passing the view controller link in which there is a pointer and button to the class that you want to access.

From there, you can access the same index value and other properties of this view controller in this class.

0
source

Source: https://habr.com/ru/post/1241871/


All Articles