AziCode
AziCode

Reputation: 2682

Increase a counter in the first interface controller by pressing a button in the second interface controller

I would like to increase the value of the property in the first interface controller in the IBAction (Add1) method of the second interface controller

and then use the value of this property to update the label when the first view controller is activated

here is the code:

First interface controller:

Blockquote

@IBOutlet weak var resultButtonLabel: WKInterfaceButton!

@IBAction func resultButton() {
  pushControllerWithName("secondInterfaceController", context: self)

}

override func willActivate() {
    super.willActivate()
    resultButtonLabel.setTitle("\(counter++)")
}

Blockquote

Second interface controller:

Blockquote

  var counter = 1

@IBAction func weScored() {
    counter++
    popController()

}

Blockquote

enter image description here

Upvotes: 1

Views: 79

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

The easy way to implement this idea is use of NSUserDefaults

In your firstViewController you can read values form NSUserDefaults this way:

override func viewDidLoad() {
    super.viewDidLoad()
    let score = NSUserDefaults().integerForKey("Score")
    resultButtonLabel.text = "\(score)"
}

and into your SecondViewController you can increase this counter with NSUserDefaults this way:

import UIKit

class SecondViewController: UIViewController {

var counter = Int()
override func viewDidLoad() {
    super.viewDidLoad()

    counter = NSUserDefaults().integerForKey("Score")
}
@IBAction func weScored(sender: AnyObject) {

    counter++
    NSUserDefaults().setInteger(counter, forKey: "Score")
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! UIViewController
    self.presentViewController(vc, animated: true, completion: nil)
    }
}

Hope this will help.

Upvotes: 1

Related Questions