UIPickerView 选择将 nil 值发送到新 ViewController

UIPickerView selection sends nil value to new ViewController

我正在尝试将 UIPickerView 的选择作为字符串传递给新的 ViewController,不幸的是,当我这样做时,返回的是 nil 值.我一直在关注几个不同的教程,但我似乎无法让它工作。如有任何建议,我们将不胜感激。

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)
    }

新 viewController 包含:

    var chosenState: String?

    override func viewDidLoad() {
        super.viewDidLoad()

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

你用错方法了func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)

你应该使用这个:

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

您需要覆盖 prepare for segue 以便 prepareForSegue 将调用并在第二个控制器中获得您选择的值。

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