Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all view controllers of a UITabBarController

I have a UITabBarController with four tabs. In each of the view controllers presented when a tab is selected I have a reset button. Tapping the button will change the appearance of all the view controllers. In particular, it will change the text of some labels in the different view controllers.

Is there some recommended way to update all the view controllers of a UITabBarController at the same time i.e. to make them reload their views?

My current approach is to make those view controllers conform to a protocol

@protocol XYReloadableViewController
- (void)reloadContents;
@end

and then send the message -reloadContents to all the view controllers when the button is tapped:

- (IBAction)touchUpInsideResetButton {
    // ...
    NSArray *viewControllers = self.tabBarController.viewControllers;
    for (UIViewController<XYReloadableViewController> *viewController in viewControllers) {
        [viewController reloadContents];
    }
}

Then in each of the view controllers I would have to implement that method:

- (void)reloadContents {
    [self.tableView reloadData];
    // other updates to UI ...
}

But that seems a little too complicated. So is there an easier way to tell the view controllers to reload their views?


Edit: And what happens if I present a UINavigationController in some of the tabs or a container view controller? I would need to pass the message along the chain of all its child view controllers...

like image 420
Mischa Avatar asked May 30 '14 09:05

Mischa


1 Answers

You can create ReloadViewController and all you contrlollers inheritance from him.

ReloadViewController have property UIButton and methods:

  1. -(void)reloadContents;
  2. -(IBAction)touchUpInsideResetButton:(id)sender;

in .m file:

-(void)viewDidLoad
{
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(reloadContents)
                                                 name:@"MyNotification"
                                               object:nil];
}

- (IBAction)touchUpInsideResetButton:(id)sender
{
  [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" 
                                                      object:nil];
}

in your viewControllers need only override method reloadContents

like image 66
Sergey Petruk Avatar answered Nov 04 '22 21:11

Sergey Petruk