FusionPointInc FusionPointInc - 2 years ago 171
Swift Question

How to pass values from a ViewController to another ViewController using a button with Swift 3.0

I am making an iOS application using Swift that is Rock, Paper, and Scissors.

When you press which a button (with Rock picture, Paper picture, or Scissors picture), it will segue to a different View Controller and display it is a tie, a win, or a loss (compares your number [ie. Rock button is 1] to a random number by the computer). But it won't display the result since it needs to be in the button, not out of the button and in the viewDidLoad().

I'll give you snippets of my code. I am using functions in the next View Controller to return a string.

So all I need help is with passing userNum and computerNum to the next View Controller in the button (when pressed) to then call the function and return the String.

var userNum: Int = 0
var computerNum: Int = 0

@IBAction func rock(_ sender: UIButton) {
userNum = 1
computerNum = (Int)(arc4random_uniform(3) + 1)
} //This next code will be in the other View Controller
func chooseWinner(userNum : Int, computerNum : Int) -> String {
if userNum == computerNum {
return "There is a tie"
}else if userNum == 1 && computerNum == 2{
return "You lost!"
}else if userNum == 1 && computerNum == 3{
return "You won!"
}else if userNum == 2 && computerNum == 1{
return "You won!"
else if userNum == 2 && computerNum == 3{
return "You lost!"
}else if userNum == 3 && computerNum == 1{
return "You lost!"
else if userNum == 3 && computerNum == 2{
return "You won!"
return "value"

Answer Source

In the Storyboard Editor, hold Ctrl while holding down leftclick and drag your mouse to the destination view controller you want to segue to. You can choose a segue type once you release your mouse, e.g. show.

This will allow you to segue to your destination view controller without having to create an IBAction programatically, like in your code.

In the source view controller, add the function

prepare(for segue: UIStoryboardSegue, sender: Any?)

which will allow you to check for a segue and do any additional setup before segueing.

Remember to set the identifier for your segue in the Attribute Inpector


Inside source viewcontroller

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "destination" {

        //OtherViewController is a placeholder for the viewcontroller class of your destination viewcontroller
        if let destinationVC = segue.destinationViewController as? OtherViewController {
            destinationVC.userNum = 1
            destinationVC.computerNum = (Int)(arc4random_uniform(3) + 1)

Inside destination view controller

var userNum: Int!
var computerNum: Int!

override func viewDidLoad() {

    //do wtv you need with your values
    print(chooseWinner(userNum: userNum, computerNum: computerNum))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download