简体   繁体   中英

How to change the background color from another ViewController?

I have two view controllers, the Home and the other that is showed by a cocoacontrol animation (MJPopupViewController) and idn the one that is showed when you push a button all the background changes, but I dont know how to change the home view controller`s background because they are not in a navigation so I cant use a self.parentViewController casting, so how can I do this? Heres the code:

- (IBAction)purple:(id)sender {
    self.view.backgroundColor = [UIColor MyPurple];

    HomeViewController *home = (HomeViewController *) self.parentViewController; <-- this didnt work, I also tried only self....

    home.view.backgroundColor = [UIColor purpleColor];


}

So I need your help, Im starting so I hope you understand, thanks!

Perhaps try:

HomeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

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

- (void)changeColor
{
    self.view.backgroundColor = [UIColor purpleColor];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

PopUpViewController

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

I suggest you to change the background color of a 'view' you need to set the backgroundColor property on it. This implies that you have access to it. If it was all in one controller you would just use

self.view.backgroundColor = [UIColor redColor];

If it was in a navigation or similar based app, then you can access a views parentViewController and change the color on it as follows:

self.parentViewController.view.backgroundColor = [UIColor redColor];

If this is not possible then you can set an iVar on the second view controller when it is created that contains the instance of the viewController that you want to change the background color on.

MyViewController* secondViewController = [[MyViewController alloc] init];
secondViewController.bgColorNeedsChangingViewController = self;

Then in the secondViewController's logic

self.bgColorNeedsChangingViewController.view.backgroundColor = [UIColor redColor];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM