简体   繁体   中英

Segue is being executed twice

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   self.selectedClubState = stateNamesForDisplay[indexPath.row]
   self.performSegueWithIdentifier ("Cities", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var clubsToPassToCitiesViewController = [clubObject]()
    if segue.identifier == "Cities" {
        for club in clubsForTable{
            if club.clubState == self.selectedClubState{
                clubsToPassToCitiesViewController.append(club)
            }
        }
       let citiesView = segue.destinationViewController as? citiesViewController
       citiesView?.clubsForChosenCity = clubsToPassToCitiesViewController
   }
}

Segue is being executed twice leading to the next VC. How can I prevent this from happening?

You are the one executing the segue twice — once automatically in the storyboard (because your segue emanates as an Action Segue from the cell prototype), and once in code when you say self.performSegueWithIdentifier . If you don't want the segue executed twice, remove one of those.

Personally, my recommendation is that you delete didSelectRow entirely and move your self.selectedClubState assignment into prepareForSegue .

Delete the current segue in storyboard. Then CTRL-drag from the viewController (not the cell) to the next view controller and name it "Cities". Now, when you select a cell, the didSelectRowAtIndexPath() will fire first and will call performSegueWithIdentifier()

在此输入图像描述

However, if all you're looking to do in the didSelectRowAtIndexPath() is get the row that performed the segue, you can maintain your original setup of having the cell segue from the storyboard, remove didSelectRowAtIndexPath() and in prepareForSegue() do:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let indexPath = self.tableView.indexPathForSelectedRow {
        self.selectedClubState = stateNamesForDisplay[indexPath.row]
    }
    var clubsToPassToCitiesViewController = [clubObject]()
    if segue.identifier == "Cities" {
        for club in clubsForTable{
            if club.clubState == self.selectedClubState{
                clubsToPassToCitiesViewController.append(club)
            }
        }
       let citiesView = segue.destinationViewController as? citiesViewController
       citiesView?.clubsForChosenCity = clubsToPassToCitiesViewController
   }
}

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