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
}
you are using the wrong method
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
You should use this: