/

Second View Controller


SecondViewController

We previously cleared out the view content of the SecondViewController in the storyboard. In this section we'll add a UIButton and a TouchUpInside delegate that will interface with the start: and stop: methods defined on the SubscribeViewController.

1 Select the Main.storyboard from the Project Explorer

2 Drag Button from the Object Library and drop it onto th View for the Second View Controller

3 Assign the Button instance as an IBOutlet in SecondViewController.h header file

    #import <UIKit/UIKit.h>

    @interface SecondViewController : UIViewController

    @property (weak, nonatomic) IBOutlet UIButton *subscribeButton;

    @end

4 Define a TouchUpInside responder for the Button in SecondViewController.m

    - (IBAction)onSubscribeToggle:(id)sender {
    }

5 With the SecondViewController.m open, import the SubscribeViewController.h header and assign a couple attributes on the internal interface

    @interface SecondViewController () {
        SubscribeViewController *subscriber;
        BOOL isSubscribing;
    }
    @end

6 Since the SubscribeViewController is not linked with the Tabbed Application we have created, we are going to pull in the View Controller and its underlying UIView to the SecondViewController so that we can view and interact with the stream.

7 Override the viewDidLoad: method of SecondViewController, instantiate the SubcribeViewController add its UIView as a subview underneath the UIButton control previously added

    - (void)viewDidLoad {
        [super viewDidLoad];

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"subscribeView"];

        CGRect frameSize = self.view.bounds;
        subscriber.view.layer.frame = frameSize;
        subscriber = (SubscribeViewController *)controller;

        [self.view addSubview:subscriber.view];
        [self.view sendSubviewToBack:subscriber.view];
    }

8 Modify the onSubscribeToggle: button delegate to invoke the start: and stop: methods on the SubscribeViewController instance

    - (IBAction)onSubscribeToggle:(id)sender {
        if(isSubscribing) {
            [subscriber stop];
        }
        else {
            [subscriber start];
        }
        isSubscribing = !isSubscribing;
        [[self subscribeButton] setTitle:isSubscribing ? @"STOP" : @"START" forState:UIControlStateNormal];
    }

9 To complete the SecondViewController, override the viewDidAppear: and viewDidDisappear: methods to properly handle the state

    -(void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [[self subscribeButton] setTitle:@"START" forState:UIControlStateNormal];
    }

    -(void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
        isSubscribing = NO;
    }