UIPickerView selection sends nil value to new ViewController

210 views Asked by At

I am trying to pass the selection of UIPickerView as a string to a new ViewController, unfortunately when I do it is returning a nil value. I have been following a few different tutorials but I cannot seem to get it to work. Any suggestions would be appreciated.

class menu: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var pickerView: UIPickerView!
    @IBOutlet weak var newsButton: UIButton!

    var pickerDataSource = ["Canterbury-Bankstown Torch", "Auburn Review", "Inner West Times", "Seniors "];
    var chosenState = String()

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView.delegate = self
        pickerView.dataSource = self
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerDataSource.count;
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerDataSource[row] as String
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        chosenState = pickerDataSource[row]
    }

    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "customSegue" {
            if let secondViewController = segue.destination as? ViewController {
                secondViewController.chosenState = chosenState
            }
        }
    }

    @IBAction func newsButton(_ sender: Any) {
        self.performSegue(withIdentifier: "customSegue", sender: nil)
    }

New viewController contains:

    var chosenState: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        finalPublication?.text = chosenState
        print(chosenState) //Just so I can see if it works
}
2

There are 2 answers

2
Satish On BEST ANSWER

you are using the wrong method func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

You should use this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "customSegue" {
        if let secondViewController = segue.destination as? ViewController {
            secondViewController.chosenState = chosenState
        }
    }
}
0
Denis On

You need to override prepare for segue so that prepareForSegue will call and you get your selected value in second controller.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "customSegue" {
        if let secondViewController = segue.destination as? ViewController1 {
            secondViewController.chosenState = chosenState
        }
    }
}