Search code examples
iosuitableviewstoryboardscene

Storyboard Two Scenes. Taking text from UITableViewCell in Scene 2 to UILabel in Scene 1


I have two scenes in the storyboard. Since I'm not allowed to upload images (new user), let's call them Scene 1 and Scene 2.

Scene 1: UITableViewCell with a UILabel, when this cell is selected, it takes you to Scene 2.
Scene 2: Provides users options to select in UITableView. Once an option is selected, it puts a check mark next to the selected UITableViewCell.

How do I get it when you click the Save button on Scene 2, it takes the text from the selected UITableViewCell in Scene 2, and takes the user back to Scene 1 and also populates the UILabel with the text from Scene 2?

I used storyboard to create the UITableViews. Each cell has it's own class. Thanks.


Solution

  • Use the delegate design pattern to allow the two objects to communicate w/ each other (Apple reference).

    In general:

    1. Create a property in scene 2 called delegate.
    2. Create a protocol in scene 2 that defines the methods a scene 2 delegate would have to define.
    3. Before the segue from scene 1 to 2, set scene 1 as scene 2's delegate.
    4. When a cell is selected in scene 2, send a message to scene 2's delegate to inform the delegate of the selection.
    5. Allow the delegate to handle the selection and dismiss scene 2 after a selection is made.

    And as an example:

    Scene 2 interface

    @class LabelSelectionTableViewController
    
    @protocol LabelSelectionTableViewControllerDelegate
      - (void)labelSelectionTableViewController:(LabelSelectionTableViewController *)labelSelectionTableViewController didSelectOption:(NSString *)option;
    @end
    
    @interface LabelSelectionTableViewController : UITableViewController
      @property (nonatomic, strong) id <LabelSelectionTableViewControllerDelegate> delegate;
    @end
    

    Scene 2 implementation

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
      UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];   
      [self.delegate labelSelectionTableViewController:self didSelectOption:cell.textLabel.text];
    }
    

    Scene 1 implementation

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
      if ([segue.destinationViewController isKindOfClass:[LabelSelectionTableViewController class]] == YES)
      {
        ((LabelSelectionTableViewController *)segue.destinationViewController).delegate = self;
      }
    }
    
    // a selection was made in scene 2
    - (void)labelSelectionTableViewController:(LabelSelectionTableViewController *)labelSelectionTableViewController didSelectOption:(NSString *)option
    {
      // update the model based on the option selected, if any    
      [self dismissViewControllerAnimated:YES completion:nil];
    }