when preparing for segue array contains no data (u

2019-02-15 12:02发布

Depending on what button is pressed I want to append a list of words to variable (pickedList) declared at the start. When I come to prepare for segue it overwrites what has been added and only using empty array that was added at the start. I am able to append items within the prepare for segue bit and these transfer over but this is not what I want. I am very very new to programming and have searched about a lot but can't seem to find what I am looking for. Thanks in advance!

Code looks like this:

class activeLiteracyOptionsViewController: UIViewController {

@IBOutlet weak var satpinButton: UIButton!
var pickedList = [String]()

@IBAction func whenSatpinButtonPressed(sender: AnyObject) {

    pickedList += ["s","a","t","p","i","n"]      
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

   let destinationViewController : flashcardsViewController = segue.destinationViewController as                flashcardsViewController

   destinationViewController.listToPlay = pickedList

1条回答
混吃等死
2楼-- · 2019-02-15 12:32

I infer from the absence of performing the segue programmatically that you must have set up both an IBAction as well as a segue from the button in Interface Builder. The problem is that the segue (and prepareForSegue) may be called before the IBAction is called. You should remove that segue, and create a new one that you'll invoke programmatically from the IBAction.

Therefore, you should not have the segue attached to the button in Interface Builder, but rather only have the button hooked up to the IBAction. You can then define a segue between the two scenes controller by control-dragging from the view controller button in the bar above the source scene to the destination scene:

enter image description here

Having added this segue between the scenes (but not from the button within the source scene), you can now select that segue in Interface Builder, go to the attributes inspector, and give that segue a unique "storyboard identifier":

enter image description here

If you gave it an identifier of SegueToSecondScene, you can now define your IBAction to set pickedList and then programmatically perform the segue:

@IBAction func whenSatpinButtonPressed(sender: AnyObject) {
    pickedList += ["s","a","t","p","i","n"]      
    performSegueWithIdentifier("SegueToSecondScene", sender: self)
}
查看更多
登录 后发表回答