Accessing a MKMapView through the tab bar
I have a tabbar application and on the first tab I have a MKMapView
. What I want to do is from somewhere else in the application, switch the active tab to the mapview and set the mapview's region based on the data in the previous view (the one with the button to switch to the mapview).
What I've tried is:
[self.tabBarController setSelectedView:0];
UIMapViewController *mapView = [self.tabBarController.viewControllers objectAtIndex:0];
[mapView displayBookmarkAnnotation:bookmark];
This just causes the app to crash unable to find the method I created. I don't think I've chosen the best path to implement this but I'm really not sure how I should go about it.
[Update]
Casting the controller returned by the tabBarController
had no effect.
[Solved]
I was trying to cast a UINavigationController
to my mapView
[self.tabBarController setSelectedView:0];
UINavigationController *navC开发者_运维技巧ontroller = [self.tabBarController.viewControllers objectAtIndex:0];
//if the tab has other views open, return to mapView
[navController popToRootViewControllerAnimated:YES];
UIMapViewController *mapView = (UIMapViewController *)[navController visibleViewController];
[mapView customMessage:object];
Are you sure the main view controller for that tab is not a UINavigationController? If so, you can get the root view controller for that which should be your UIMapViewController.
It would be good to put a direct reference in the AppDelegate though if you are going to be calling it from elsewhere.
Why not route it through your AppDelegate? The AppDelegate can have a UITabBarController
and the MKMapView
(both wired through interface builder.) The UIButton
handler would then also be in the AppDelegate so that it can call -[UITabBarController setSelectedView:]
and -[MKMapView setRegion:]
.
What you want to do is create a subclass or a category of the UITabBarController that
- registers for NotificationCenter events that you define
- handles the events with a new selector. I generally use do/did naming convention for them.
When the event comes through you set the selectedIndex.
精彩评论