0

我试图将UIPickerView作为字符串的选择传递给 new 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
}
4

2 回答 2

1

你使用了错误的方法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
        }
    }
}
于 2018-10-04T06:13:25.777 回答
0

您需要覆盖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
        }
    }
}
于 2018-10-04T06:17:44.163 回答