Swift : Access variable in ViewController

2019-03-06 16:38发布

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.

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-06 17:07

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.

查看更多
做个烂人
3楼-- · 2019-03-06 17:09
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楼-- · 2019-03-06 17:19

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
查看更多
成全新的幸福
5楼-- · 2019-03-06 17:19

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)")
    
查看更多
登录 后发表回答