when preparing for segue array contains no data (using swift)

回眸只為那壹抹淺笑 提交于 2019-12-19 04:44:10

问题


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:


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:

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":

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


来源:https://stackoverflow.com/questions/27697227/when-preparing-for-segue-array-contains-no-data-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!