简体   繁体   中英

How do I pass data from a View controller into my pop up view controller (swift/ios)

I'm quite new with Swift and I'm making this mini game type app that counts the score and updates the label in the view controller. I want to pass that score from a view controller into another external pop up view controller I created.

@IBAction func Button7Tapped(_ sender: AnyObject)
    {
        if Index == 13 {
            game.score += 1
        } else {
            let scorepopVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "finalScorePop") as! finalScoreViewController

            self.addChildViewController(scorepopVC)
            scorepopVC.view.frame = self.view.frame
            self.view.addSubview(scorepopVC.view)
            scorepopVC.didMove(toParentViewController: self)
        }
        updateGame()
    }

Above is my code for the external pop up view controller I created, which also has a separated .swift file. How would I go about taking my game.score and passing that into my Popup view controller?

In your finalScoreViewController swift file add a new property.

final class FinalScoreViewController: UIViewController {
    var score: Int?


}

And then just assign it when you're instantiating it.

@IBAction func Button7Tapped(_ sender: AnyObject) { 
    if Index == 13 {
        game.score += 1
    } else { 
        let scorepopVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "finalScorePop") as! finalScoreViewController

        scorepopVC.score = game.score //THIS LINE

        self.addChildViewController(scorepopVC)
        scorepopVC.view.frame = self.view.frame
        self.view.addSubview(scorepopVC.view)
        scorepopVC.didMove(toParentViewController: self)
    }
    updateGame()
}

It is better to use storyboard to open the ViewController. In storyboard, right click and drag from you button to the second view controller (the one that you wish to open).

Choose the segue type that you wish to use. In your case, I think Present Modally will work fine.

在此处输入图片说明

You will see a line between the two UIViewControllers in storyboard. That is the segue. Tap on it. In the Attributes inspector give the segue an identifier. For instance "myFirstSegue".

在此处输入图片说明

Then in the code of the UIViewController that contains your button override prepare(for:sender:). This method is called when preparing for the segue to happen. Iow when you tap on the button. You have access to the destination UIViewController and can therefor access and set the properties on it.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "myFirstSegue" {
        if let vc = segue.destination as? MyViewController {
            //here you set your data on the destination view controller
            vc.myString = "Hello World"
        }
    }
}

Note that we check the identifier, because all segues that go from this ViewController to other ViewControllers will call prepare(for:sender:)

It's quite simple, Just add a property in your finalScoreViewController (if you are not already done this) and -for example- call it score:

class finalScoreViewController: UIViewController {

    var score: String?

    // ...

Add this line to the Button7Tapped action (where you set a value for finalScoreViewController's score):

let scorepopVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "finalScorePop") as! finalScoreViewController

        // add this line:
        scorepopVC.score = "My score"


        self.addChildViewController(scorepopVC)
        scorepopVC.view.frame = self.view.frame
        self.view.addSubview(scorepopVC.view)
        scorepopVC.didMove(toParentViewController: self)

Finally, in finalScoreViewController :

override func viewDidLoad() {
    super.viewDidLoad()

    if let scr = score {
        print(scr)
    }
}

Hope that helped.

You do not actually have to pass the variable to the next view controller. All you have to do is create a variable outside of the View Controller class, and voila, you can access your variable from anywhere, in any swift file. For example:

var score = 0

class ViewController: UIViewController {

    override func viewDidLoad(){
        super.viewDidLoad()
        
    }
    @IBAction func Button7Tapped(_ sender: AnyObject){
        score += 1
    }
}

And then in the other View Controller, you would have something like this:

@IBOutlet weak var scoreLabel: UILabel!

class ViewController: UIViewController {
    override func viewDidLoad(){
        super.viewDidLoad()
        var timer1 = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateScore), userInfo: nil, repeats: true)
    }

@objc func updateScore() {
    scoreLabel.text = "You have \(score) points!"
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM