0

新来的 swift,希望我能得到答案。我需要将 NSArray 传递给下一个视图控制器,并在按下按钮时以随机顺序传递。我在第二个视图控制器中声明了 UILabel 和一个变量,segue 似乎工作。唯一的问题是它没有传递任何价值。这是我的代码。

    @IBAction func ressedbutton(_ sender: Any) {

    let quotes: NSArray = ["Quote 000", "Quote 001", "Quote 002"]

    let range: UInt32 = UInt32(quotes.count)

    let randomNumber = Int(arc4random_uniform(range))
    let QuoteString = quotes.object(at: randomNumber)

   // self.resul.text = QuoteString as? String





    performSegue(withIdentifier: "showresult", sender: QuoteString)

    let myVC = storyboard?.instantiateViewController(withIdentifier: "result") as! result

    myVC.stringPassed =
        (QuoteString as? String)!



}

第二个视图的代码是

类结果:UIViewController {

var stringPassed = ""
@IBOutlet weak var ResultLabel: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()

    ResultLabel.text = stringPassed

我认为我的问题出在 myvc.stringpassed=...?如何随机传递我拥有的数组?

提前致谢。

4

3 回答 3

1

您需要做的是将该值与senderin一起传递,performSegue然后访问该值prepare(for:sender:)并将该值传递给destinationController。

performSegue(withIdentifier: "showresult", sender: QuoteString)

现在senderprepare(for:sender:)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? result, let data = sender as? String {
        vc.stringPassed = data
    }
}
于 2017-05-09T11:04:29.383 回答
0

您必须使用 prepare(for segue: UIStoryboardSegue, sender: Any?) 方法将数据分配给 toViewController.UIStoryboardSegue 对象 segue 具有标识符、目标和源等属性。

在此方法中,首先检查标识符,如果它匹配将目标控制器转换为您的自定义视图控制器并将数据分配给视图控制器对象。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "showresult"{
        if let toViewController = segue.destination as? result {
            vc.stringPassed = QuoteString
        }
    }

}
于 2017-05-09T11:10:40.550 回答
0

尝试这种方式删除 segue 将 Storyboard ID 提供给您想要传递数据的视图控制器并将相同的 Storyboard ID 粘贴到下面(YourIdentifier)

    @IBAction func ressedbutton(_ sender: Any) {

    let quotes: NSArray = ["Quote 000", "Quote 001", "Quote 002"]

    let range: UInt32 = UInt32(quotes.count)

    let randomNumber = Int(arc4random_uniform(range))
    let QuoteString = quotes.object(at: randomNumber)

   // self.resul.text = QuoteString as? String

  let vc  = storyboard?.instantiateViewController(withIdentifier:"YourIdentifier") as! YourNextViewController


        vc.stringPassed = (QuoteString as? String)!


        self.present(vc, animated: true, completion: nil)

}
于 2017-05-10T04:42:43.780 回答