Search code examples
swiftxcode8ios10apple-developer

pass NSArray to next viewcontroller in swift


New to swift, hope I will get my answer. I need to pass NSArray to next view controller and in random order when button is pressed. I have UILabel and one variable declared in second view controller and segue seems working. Only peoblem is it does not pass any value. Here is my code.

    @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)!



}

and code for second view is

class result: UIViewController {

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


override func viewDidLoad() {
    super.viewDidLoad()

    ResultLabel.text = stringPassed

I think my problem is in myvc.stringpassed=...? How to pass the arry I have and in randomly?

Thanks in Advance.


Solution

  • What you need to do is pass that value with sender in performSegue and after that access that value in prepare(for:sender:) and pass the value to destinationController.

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

    Now use this sender argument in prepare(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
        }
    }