Search code examples
iosobjective-ccolorsuiappearance

Change all the app color scheme


So, I have a HomeViewController (picture 1) with two buttons, one white and one blue. On the right bottom corner you can see a button which modally presents a SettingsViewController (picture 2), on this view controller there are 4 buttons so the user can choose which color scheme do they prefer. Imagine the user press the first one (red) then, when dismissing the view controller the color scheme of HomeViewController should look like picture 3.

enter image description here

Any ideas on how to do this on a efficiently/simple way?.


Solution

  • There are two good ways you could do this: 1) Delegation, and 2) viewWillAppear:.

    For delegation, you'll need to define a protocol. Your HomeViewController will be a delegate for this protocol, and your SettingsViewController will call it.

    //SettingsViewController.h
    
    @protocol SettingsDelegate <NSObject>
    @required
    -(void)colorChanged:(UIColor *)color;
    @end
    
    @interface SettingsViewController : UIViewController
    
    @property (nonatomic, weak) id<SettingsDelegate> delegate;
    
    @end
    

    Somewhere when the settings view controller is set up, make sure to set self.delegate equal to a reference to HomeViewController. This is a must.

    Then, when your user changes the color, call:

    [self.delegate colorChanged:whateverColor];
    

    Your delegate must obviously observe this method, and change the color appropriately:

    -(void)colorChanged:(UIColor *)color {
    
        [myButton setBackgroundColor:color];
    }
    

    For viewWillAppear:, just save the color somewhere and set the color of your button in your view controller's method for this. viewWillAppear: will get called when your settings view is about to disappear and show the home view controller:

    -(void)viewWillAppear:(BOOL)animated {
    
        [super viewWillAppear:animated];
    
        [myButton setBackgroundColor:mySavedColor];
    }