简体   繁体   中英

Swift passing data between views

I am working on a Swift app and I've run into a slightly weird issue. I'm quite new to Swift and iOS development so think I may not be doing this the correct way.

I have a UITableView and I am able to read the contents of the selected cell without issue:

override func tableView(_ tableView: UITableView, didSelectRowAt 
indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath)
    selectedItem = (cell?.textLabel?.text)!
}

I have a variable set at the top of my class like so:

var selectedItem: String = String()

I then use a prepare for seque to seque to the new page/view and pass in the data selected:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetails"
    {
        if let destinationVC = segue.destination as? ItemDetails {
            destinationVC.detailsToDisplay = selectedItem
        }
    }
}

The problem is that while the data does get passed between the views and appears in the UI, it's not the most recent data. For example when I run the code and select the item, the first time, nothing appears, but if I click the back button, select the item again, this time it does appear in the next view. And on subsequent selections in the UI, it navigates to the next view but doesn't update the text until I pick another item.

In my mind it's almost like the selectedItem variable is not being set on each selection as I expect and passed through, but instead on subsequent selections in the UI, it is updated.

How do I get this to pass the actual correct item each time and not the previous one or none at all (which is what happens on the first run).

Thanks!

Your prepare for segue called before the didSelectRow at index

change the code like below

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetails"
    {
        if let destinationVC = segue.destination as? ItemDetails {



let cell = tableView.cellForRowAtIndexPath(self.tableView.indexPathForSelectedRow!) as UITableViewCell

destinationVC.detailsToDisplay = (cell.textlabel?.text)!

        }
    }
}

If you want to pass data between controllers, you can create a global variable declared above the class. Store the result in that global variable.

For example,

In ViewController class:

var result:String!
class ViewController:UIViewController{
result = // your data }

In SecondViewController class:

class SecondViewController:UIViewController{
var fetch = result
if(fetch != result){
print("Got the value")
}
else
{
print("Null value")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM