Using the Storyboard Segue

When we tap a cell in the list of tweets, we navigate to the new view controller, which we’ll customize to show the details for the selected tweet. But hold on—how do we know which tweet was selected? And how will we communicate that to the other view controller?

This is where the segue can help us. Prior to performing a transition between view controllers, the current view controller gets a callback on the method prepareForSegue, passing in details of the transition in a UIStoryboardSegue object. As inherited from UIViewController, this method does nothing, but we can override it to take some interesting action, based both on our current state and details of the segue.

The UIStoryboardSegue object provides properties for the sourceViewController, destinationViewController, and an identifier, which is a string that we can use to distinguish between different segues in the storyboard. It’s a good habit to name any segue we intend to use in code, so click on the segue’s circle icon between the two view controllers and display the Attributes Inspector. The main attributes we can edit are the Identifier string and the segue kind (which is whatever we set in the HUD when we created the segue: Show, Show Detail, Present Modally, and so on). There is also a Segue Class and Segue Module, which would be used for running custom code to perform the segue. All we need at this point is to name the segue, so for the identifier, enter showTweetDetailsSegue.

Now visit RootViewController.swift. Write a new method to override prepareForSegue:

 override​ ​func​ prepareForSegue(segue: ​UIStoryboardSegue​,
  sender: ​AnyObject​?) {
 if​ segue.identifier == ​"showTweetDetailsSegue"​ {
 if​ ​let​ row = tableView?.indexPathForSelectedRow?.row {
 let​ parsedTweet = parsedTweets[row]
 NSLog​ (​"tapped on ​​(​parsedTweet.tweetText​)​​"​)
  }
  }
 }

When called, this looks at the segue argument to see if it matches the identifier we put in the storyboard: showTweetDetailsSegue. If it does, it gets the selected row from the table, looks up the corresponding tweet, and logs its text to the console. Run the app and tap a row to verify this is working; if not, check the spelling of the segue identifier in the storyboard and the code to make sure they match exactly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.62.239