prepareforsegue vs performwithsegue if statements. - ios

Suppose I have a table view, how would i go about creating code to have one cell go to one view controller and then have another cell to a second view controller. Specifically the prepare for segue and perform with segue if statements.

Your parent view controller (where the table view lives) should have your UITableViewDelegate methods.
You'll need to create your own implementation of:
optional func tableView(_ tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath)
And in there (which gets called when a cell is pressed), you'll want to call
self.performSegueWithIdentifier("Load View", sender: self)
One of the parameters passed into didSelectRowAtIndexPath is the index path row, so you know which row the user pressed. And you can pass along that cell (or the information, or the object that the cell is drawing it's contents from) in the "sender" parameter of the performSegueWithIdentifier method.
You'll have direct access to the child view controller from the parent in the prepareForSegue:sender: method. So you can do something like:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "Load View") {
// pass data to next view
let cellData = sender as YourDataObject
let childViewController = segue.destinationViewController as YourChildViewController
// and now you can directly set whatever custom fields / bits
// you need to set in your destination view controller
}
}
Makes sense so far?

Related

Swift dynamic view based on cell tapped in previous table view

I have a table view with a list of events. I now am trying to create a dynamic view that can show details about all of those events based on the event tapped on. Two questions I have are how do I create a generic segue that I can use for any table cell to go to the same view, and then in that view how do I access the cell that brought the user to the view?
You would use didSelectRowAtIndexPath. First, create a variable eventToPass of type Event (or whatever your class is called) on your ViewController. Then, you should get the object that represents your data, then pass that to your new UIViewController. Something like:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let event = eventsArray[indexPath.row]
self.eventToPass = event
self.performSegueWithIdentifier("EventSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "EventSegue") {
var detailVC = segue.destinationViewController as EventDetailViewController
detailVC.event = eventToPass
}
}
This assumes that you have a ViewController called EventDetailViewController that has a property called event. From here, you can access any of the event's details on your new ViewController.

How to save a value from didSelectRowAtIndexPath and carry it to another tableView (SWIFT)

In my first table view I have an array which populates the table view. The user then clicks a cell. Each cell has a different text label. I want to carry the label value from one table view to the next, but when it gets to the other table view the variable I try to set it to is nil. I am using segues and have tried to use prepareForSeguge function. I just can't get the variable to save once it's left the didSelectRowatIndexPath method.
EDIT: I used an observer to check that my variable was being set, but it isn't set until after all other functions have run. How Would I then be able to use my variable in my second tableview to populate the table?
Here is my code:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;
GenreSelector = currentCell.textLabel!.text
print(GenreSelector)
performSegueWithIdentifier("letsGo", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "letsGo") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destinationViewController as! ResultTableViewController
// your new view controller should have property that will store passed value
viewController.GenreSelection = GenreSelector
}
}

Swift - Tell TableViewController what data to populate with

I have a table view populated with cells containing the user's friends. A cell, when selected, should pull up that friend's profile. However, while the profile view does show up, I don't know how to tell its view controller to load that friend's profile data. How do you have two view controllers communicate with each other in response to user action? Thanks in advance.
Let's have two view controllers:
destinationVC and sourceVC
Create optional variables in destinationVC to store values which you want to share between the VC's.
In the sourceVC
override prepareForSegue method
obtain the destinationVC using segue.destinationViewController and store the returned value in a variable, say destVC
initialise the optional variables of destVC with values from selected cell
you can obtain the selected cell by using tableview.cellForRowAtIndexPath(tableView.indexPathForSelectedRow())
get data from selected cell and assign it to destVC's variables
Then in the destVC
In the viewDidLoad method
Check if the optional variables are not nil
Use the values of variables to load/update the destVC.
Edit: Updated answer according to Mike Taverne's comment.
You need to set the "user" property of that "destination" view controller in your current view controller:
Set a selectedUser property in your current view controller:
class CurrentTableViewController: TableViewController {
var selectedUser: AnyObject?
...
}
Then when that friend's cell is selected, set the "selectedUser" property in "didSelectRowAtIndexPath":
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedUser = // get the user property depending on how you're defining your table cells in the first place
self.performSegueWithIdentifier("pushToUser", sender: self)
}
Next in your prepareForSegue method, define the destination view controller and set its "user" property from the "self.selectedUser" property:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "pushToUser") {
var userProfileTableViewController: UserProfileTableViewController = segue.destinationViewController as UserProfileTableViewController
userProfileTableViewController.user = self.selectedUser
}
}
Last, in the destination view controller (which in this case is UserProfileTableViewController) you can call your database queries, etc. using "self.user".

Swift: Make button trigger segue to new scene

Alright, so I have a TableView scene and I'm going to put a button in each of the cells and I need each cell to, when clicked, segue to its own ViewController scene. In other words, I need to know how to connect a button to a scene (The only button I have right now is "milk")
I know how to create an IBAction linked to a button, but what would I put in the IBAction?
I'm a beginner so I need a step-by-step explanation here. I've included a picture of my storyboard. I haven't written any code yet.
If you want to have a button trigger the segue transition, the easiest thing to do is Control+Click from the button to the view controller and choose a Segue option (like push). This will wire it up in IB for you.
If you want to write the code to do this yourself manually, you can do so by naming the segue (there's an identifier option which you can set once you've created it - you still need to create the segue in IB before you can do it) and then you can trigger it with this code:
V2
#IBAction func about(sender: AnyObject) {
performSegueWithIdentifier("about", sender: sender)
}
V3
#IBAction func about(_ sender: Any) {
performSegue(withIdentifier: "about", sender: sender)
}
You can use the delegation pattern. Presuming that you have implemented a custom table cell, you can define a property in its class to hold whatever you think is helpful to identify the row - it can be its index, or (my preferred way) an instance of a class which represents the data displayed in the cell (I'm calling it MyCellData.
The idea is to let the cell notify the table view controller about a tap on that button, passing relevant data about (the data displayed in) the row. The table view controller then launches a segue, and in the overridden prepareForSegue method it stores the data passed by the cell to the destination controller. This way if you have to display details data about the row, you have all the relevant info, such as the details data itself, or an identifier the destination view controller can use to retrieve the data for example from a local database or a remote service.
Define a protocol:
protocol MyCellDelegate {
func didTapMilk(data: MyCellData)
}
then declare a property named delegate in the cell class, and call its didTapMilk method from the IBAction
class MyTableCell : UITableViewCell {
var delegate: MyCellDelegate?
var data: MyCellData!
#IBAction func didTapMilk() {
if let delegate = self.delegate {
delegate.didTapMilk(self.data)
}
}
}
Next, implement the protocol in your table view controller, along with an override of prepareForSegue
extension MyTableViewController : MyCellDelegate {
func didTapMilk(data: MyCellData) {
performSegueWithIdentifier("mySegueId", sender: data)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "mySegueId" {
let vc: MyDestinationViewController = segue.destinationViewController as MyDestinationViewController
vc.data = sender as? MyCellData
}
}
}
Of course you need a data property on your destination view controller for that to work. As mentioned above, if what it does is displaying details about the row, you can embed all required data into your MyCellData class - or at least what you need to retrieve the data from any source (such as a local DB, a remote service, etc.).
Last, in cellForRowAtIndexPath, store the data in the cell and set its delegate property to self:
extension MyTableViewController : UITableViewDataSource {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let data: MyCellData = retrieveDataForCell(indexPath.row) // Retrieve the data to pass to the cell
let cell = self.tableView.dequeueReusableCellWithIdentifier("myCellIdentifier") as MyTableCell
cell.data = data
cell.delegate = self
// ... other initializations
return cell
}
}
Use self.performSegueWithIdentifier("yourViewSegue", sender: sender) under your event for handling button's click:
#IBAction func redButtonClicked(sender: AnyObject) {
self.performSegueWithIdentifier("redView", sender: sender)
}
In the above code, redView is the segue identifier.

Set variable before segue transition happens

I have a UITableView which I have set up to go to a different VC when a row is selected by the user (the table only consists of one array). I want to pass the row index of the selected item. I am using didSelectRowAtIndexPath to set a variable named selectedCellIndex to the row index. However, since I also have the tableView set up to go to the next VC prepareForSegue fires off (or around the same time) as didSelectRowAtIndexPath. As a result the first time I select an item from the list the value sent is nil, after that I always get the previous value of the row selected. Any Ideas on how to make sure that the variable is set before the app transitions to the next segue without putting a pause?
Here is my code:
var selectedCellIndex:Int!
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
var indexPath = tableView.indexPathForSelectedRow() as NSIndexPath?
selectedCellIndex = indexPath?.row as Int?
}
//SEGUE
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "signature" {
let vc = segue.destinationViewController as SignatureViewController
vc.index = "\(selectedCellIndex)"
}
}
Thanks
You can get the selected index path from the table view directly using the indexPathForSelectedRow method. There is no need to implement didSelectRowAtIndexPath just to store the selected index.
The prepareForSegue: method is the only method where you should set/access variables that are necessary for a transition.

Resources