0

I'm developing a simple game (my first iOS app!) and am trying to link a variable between two View Controllers. In the first view controller, I have a textfield where the user can type in any number they choose. In the second View Controller, I would like users to be able to generate any number between 1 and the number they entered by pressing a button and be able to keep doing so. However, I am not able to use the "upperBound" variable holding the user-entered value in ViewController2.

I've tried using prepare for segue but it's not working, and I've snooped around stackoverflow and tried a couple of methods without quite knowing what I'm doing to no avail.

(UPDATED) ViewController:

class ViewController: UIViewController, UITextFieldDelegate {

//MARK: Properties

@IBOutlet weak var numberOfPages: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    // Handle the text field’s user input through delegate callbacks.
    numberOfPages.delegate = self

}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}

func textFieldDidEndEditing(_ textField: UITextField) {

//Save number entered and then randomly select a number within bounds
}


//MARK: Actions

var upperBound: Int?
@IBAction func setUpperBound(_ sender: UIButton) {
upperBound = Int(numberOfPages.text!)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

    // Create a variable that you want to send
    var newUpperBound = Int(upperBound!)

    // Create a new variable to store the instance of ViewController2
    let destinationVC = segue.destination as! ViewController2
    destinationVC.upperBound = newUpperBound
}

}

(UPDATED) ViewController2:

class ViewController2: UIViewController, UITextFieldDelegate {


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
}
*/

//Mark: Actions
@IBAction func roller(_ sender: UIButton) {
    //Generate random number
    let randomNumber = Int.random(in: 0 ..< upperBound)
}
var upperBound: Int?
}

With this code, I'm getting an error on line 34 of ViewController2 that reads "Use of unresolved identifier upperBound". Additionally, there is an issue on line 40 of ViewController that reads "immutable value upperBound was never used". I would expect to be able to generate a random value between 1 and the entered number so that I can keep working and add more features to my app (like printing these random values etc)

Rohit
  • 1
  • 1
  • http://www.apeth.com/swiftBook/ch03.html#_variable_scope_and_lifetime – matt Jul 27 '19 at 04:15
  • How do you go from ViewController1 to ViewController2 ? You can pass value from 1ViewController to other while moving to other – Yogesh Tandel Jul 27 '19 at 04:31
  • @YogeshTandel not sure I understand your question. I have created two ViewControllers and connected them by segue method (control click and connect). – Rohit Jul 27 '19 at 04:41
  • check this out - https://stackoverflow.com/questions/26207846/pass-data-through-segue – Yogesh Tandel Jul 27 '19 at 04:44
  • @YogeshTandel thanks, I took a look, but I'm still confused on one thing. The variable that I wish to move is under an IBAction function, so how can I declare it under the viewController class? – Rohit Jul 27 '19 at 04:58
  • check the code below. – Yogesh Tandel Jul 27 '19 at 05:05

1 Answers1

0

ViewController

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var numberOfPages: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    numberOfPages.delegate = self
}

//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {
    //Save number entered and then randomly select a number within bounds
}

//MARK: Actions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if numberOfPages.text == ""{
        print("Please enter number")
        return
    }
    let upperBound: Int? = Int(numberOfPages.text ?? "0")

    if upperBound != 0{
        if segue.identifier == "mySegue"{
            let vc = segue.destination as! ViewController2
            vc.upperBound = upperBound
        }
    }
}
}

ViewController2

import UIKit

class ViewController2: UIViewController {

@IBOutlet weak var lbl_UpperBound: UILabel!
@IBOutlet weak var btn_Generate: UIButton!
@IBOutlet weak var lbl_Random: UILabel!

var upperBound: Int?

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    lbl_UpperBound.text = "Upper Bound - \(upperBound ?? 0)"
    btn_Generate.addTarget(self, action: #selector(roller), for: .touchUpInside)
    lbl_Random.text = ""
}


@objc func roller(_ sender: UIButton) {
    //Generate random number
    let randomNumber = Int.random(in: 0 ..< (upperBound ?? 1))
    lbl_Random.text = "\(randomNumber)"
}

}

Also Don't forget to name the Segue

enter image description here

Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25
  • Doesn't the var upperBound: Int? part go in ViewController2? – Rohit Jul 27 '19 at 05:10
  • yes.. add it to your second view controller and pass data from first to second – Yogesh Tandel Jul 27 '19 at 05:18
  • ok I added everything, but I'm getting on the prepareForSegue line in ViewController: "method does not override any method from its superclass" – Rohit Jul 27 '19 at 05:24
  • Wait. i will send you a sample – Yogesh Tandel Jul 27 '19 at 05:33
  • Hey man, thanks so much! I will check this tomorrow as it is quite late where I live and I will get back to you if I have any issues or questions. Thanks again for taking the time to help me! I'm just starting out with iOS development so this is really helpful – Rohit Jul 27 '19 at 06:25