Bill Skrzypczak
Bill Skrzypczak

Reputation: 35

Passing data thru a Swift segue works every other time

I have a tableview which reads and RSS feed of episodic radio shows. I want the playlist for the selected show to pass to a second controller for viewing in a textview when a cell is selected. I am using a segue and it works when I select the same cell twice (every other time). I have searched everywhere without success and its driving me nuts! Please help. Here is my code

     // Only grab the data at the selected cell
        //
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        // Load the variable to hold whats in the row
        currentList = feeds.objectAtIndex(indexPath.row).objectForKey("itunes:summary") as NSString

        // Load the row number
        myRow = (indexPath.row)

    }

    // Pass the data thru the segue
    override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
        if (segue.identifier == "mySegue") {

//            var vc = segue.destinationViewController as secondViewController
//            vc.toPass = currentList
//            println(vc.toPass)



            let vc = segue.destinationViewController as secondViewController
            let indexPath = self.tableView.indexPathForSelectedRow
            vc.toPass = currentList
        }
    }
}

Here is the code from my second view controller

 import UIKit

class secondViewController: UIViewController {

    // Create a property to accept the data

    @IBOutlet weak var textPlayList: UITextView!



    // Create a variable to store the data

    var toPass:String!

    override func viewDidLoad() {
        super.viewDidLoad()



        textPlayList.text = toPass
        textPlayList.textColor = UIColor .whiteColor()
        textPlayList.font = UIFont .boldSystemFontOfSize(10)

    }


}

Upvotes: 1

Views: 397

Answers (1)

vacawama
vacawama

Reputation: 154593

The problem is that prepareForSegue happens before didSelectRowAtIndexPath so your currentList variable is set up too late for be useful in prepareForSegue.

To fix this, move this code:

    // Load the variable to hold whats in the row
    currentList = feeds.objectAtIndex(indexPath.row).objectForKey("itunes:summary") as NSString

to prepareForSegue:

    override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) {
        if (segue.identifier == "mySegue") {
            let vc = segue.destinationViewController as secondViewController
            if let indexPath = self.tableView.indexPathForSelectedRow() {
                let currentList = feeds.objectAtIndex(indexPath.row).objectForKey("itunes:summary") as NSString
                vc.toPass = currentList
            }
        }
    }

In general, you don't need didSelectRowAtIndexPath if you are using segues because prepareForSegue is where you set up the transition.

Upvotes: 1

Related Questions