Search code examples
uiviewcontrollerpropertiesswift4ios11

Accessing @IBAction's property of ViewController and pass it to SecondViewController


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()
    }
}

Solution

  • 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)