Search code examples
iosobjective-cmethodsupdating

Page View Controller update view controllers ?


I have a page view controller and each time the user swipes I use this method to detect if the transition completed.

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed

Now I have 5 view controllers that I display in my page view controller, and each of those view controllers have a UILabel on them. Using the method above to detect a successful transition, I want to update the UILabels with data from the page view controller class each time the transition completes.

So every time the user swipes I want the UILabels on the 5 view controllers to be updated with new values from my page view controller class.

What is the best way to do this, (regularly updating strings/calling methods from a different class)? I have looked around and I couldn't find anything about this?! Any help would be greatly appreciated, thanks.


Solution

  • The best way I found to do this guys is through NSNotifications. I create an observer in each of my view controller classes I want to update, then I simply call the Notifications in the main class and the view controllers then call a method inside them! So simple and clean!

    Add this in the class you want to be updated:

     [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(updateLabel:)
                                                     name:@"LABELUPDATENOTIFICATION1"
                                                   object:nil];
    

    Create a method for it:

    - (void)updateLabel:(NSNotification*)notification
    {
        NSString *updatedText = (NSString*)[notification object];
        [nameLabel setText:updatedText];
    }
    

    Then call this from any other class and the method you created will be called:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"LABELUPDATENOTIFICATION1"object:content1];
    

    I am very surprised no one suggested this to me from the beginning, as this is so simple, all the other answers seemed so complex.