Communicating between 2 ViewControllers in Tab Bar Controller Project

user2621075 picture user2621075 · Sep 7, 2013 · Viewed 7.7k times · Source

I'm using a Tab Bar Controller in my project where the FirstViewController has a Mapbox map view and the SecondViewController has buttons that when pressed add a tile layer to the map view. Here's what I've tried. It creates error ***Use of undeclared identifier '_mapView' in the SecondViewController.m

//FirstViewController.h

#import <UIKit/UIKit.h>
#import <MapBox/MapBox.h>
#import "SecondViewController.h"
#import "SecondViewController.m"

@interface FirstViewController : UIViewController


@property (strong, nonatomic) IBOutlet RMMapView *mapView;


@end


//SecondViewController.h

#import <UIKit/UIKit.h>
#import <MapBox/MapBox.h>
#import "FirstViewController.h"
#import "FirstViewController.m"


@interface SecondViewController : UIViewController

- (IBAction)stationingLayerButton:(id)sender;

@end


//SecondViewController.m

- (IBAction)stationingLayerButton:(id)sender {

RMMBTilesSource *stationingMap = [[RMMBTilesSource alloc] initWithTileSetURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Stationing20" ofType:@"mbtiles"]]];


[_mapView addTileSource:stationingMap atIndex:2]; 

 }
}

The map calls are correct because I've tested it on a project that only uses one view controller. Now that I'm trying it on a Tab Bar Controller I get this error.

My question is

1.how do I get mapView in the FirstViewController to respond to calls in the SecondViewController? 2.Can this be done? I've imported the class files thinking this would open communication between the two but I'm stuck with this error.

Answer

Mrunal picture Mrunal · Sep 7, 2013

Using tabbar controller you can get array on all associated view controllers.

You can find more details here: UITabbarController - viewControllers property

For example :

In a tabbar, if we have two view controllers, let say VC1 and VC2, then we can have any of these reference by using below code snippet.

Accessing VC1 reference in VC2 class implementation (VC2.m):

VC1 *myVC1ref = (VC1 *)[self.tabBarController.viewControllers objectAtIndex:0];

Now we can use public properties and methods of VC1 class and it will give the same reference which tabbar has loaded.

Hope this helps.