0

How to access points property from IBAction method of ViewController and pass it to scoreLabel of SecondViewController?

import UIKit

class ViewController: UIViewController {
    var points: Int = 0

    @IBAction func action(sender: UIButton) {
        points += 1
    }
}



class SecondViewController: UIViewController {
    @IBOutlet weak var scoreLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220

1 Answers1

1

Note: This is assuming that you are segueing to SecondViewController from ViewController.

In SecondViewController, declare a variable called score or something like that:

var score: Int = 0

In ViewController, implement the prepareForSegue method like so:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "YourSegueIdentifierForSecondViewController" {
        if let secondViewController = segue.destination as? SecondViewController {
            secondViewController.score = points
        }
    }
}

Then in SecondViewController's viewDidLoad, you can set score to your label:

scoreLabel.text = String(score)
Xcoder
  • 1,433
  • 3
  • 17
  • 37