Search code examples
iosobjective-cuitableviewuistoryboardsegue

Change text color based on which segue/VC was the source


I did a little research but most examples are still going one ViewController to one ViewController: I have 4 TableViewControllers going to one TableViewController.

I have a simple array on detailsTableViewController. For one item in my array (which is displaying on a table), I want it to be a different color based on which TableViewController this page was called from. I have four different TableViewControllers which have a button with segue to detailsTableViewController, so I want to know which of these I came from.

Then I want to do this:

if (indexPath.row == 1)
    { cell.detailTextLabel.textColor = [UIColor someColor];}

So the logic of what I need is:

if (calledSegue="fromRed")
    {if (indexPath.row == 1)
        {cell.detailTextLabel.textColor = [UIColor redColor];}}
else if (calledSegue="fromYellow")
    {if (indexPath.row == 1)
        {cell.detailTextLabel.textColor = [UIColor yellowColor];}}
else if (calledSegue="fromGreen")
    {if (indexPath.row == 1)
        {cell.detailTextLabel.textColor = [UIColor greenColor];}}
else if (calledSegue="fromBlack")
    {if (indexPath.row == 1)
        {cell.detailTextLabel.textColor = [UIColor blackColor];}}

Can someone help me figure out what I need to do to make this work? Again, I need to figure out which TableViewController was the segue's source and then change the text color for indexPath == 1 based on that information.

Each segue has a separate identifier as you see in my sample code idea.

Thanks


Solution

  • You should use the method prepareForSegue:sender: for this kind of job.

    First of all, add a property firstRowColor to your detail controller, so you can use it on your tableView delegate.

    Then in each one of your sources view controller, override the method prepareForSegue:sender:. This method gets called when a segue is about to be performed, in order to pass data along view controllers. Try something like this:

    - (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
    {
       // Check if the segue is the right one
       if ([segue.identifier isEqualToString:kDetailSegueIdentifier]) {
           // Specify the right color for this source view controller
           [(DetailViewController*)segue.destinationViewController setFirstRowColor:[UIColor redColor]];
       }
    }