简体   繁体   中英

Alter UIView elements outside viewDidLoad

I have an EventsManager class that communicates with my view controller. I would like to be able to update UIView elements (images, progress bar, etc) by calling methods inside my view (like updateProgressBar, for example) from the EventManager class.

However, anytime I try to update UIView elements from within any method in my view other than viewDidLoad , it's just ignored entirely.

Is there anything I'm missing?

Super simple example:

This works

- (void)viewDidLoad
{
  progressBar.progress = 0.5;
}

This does not (this method is in my view controller)

- (void)updateProgressBar:(float)myProgress
{
  NSLog(@"updateProgressBar called.");
  progressBar.progress = myProgress;
}

So, if I call:

float currentProgress = 1.0;

ViewController *viewController = [[ViewController alloc] init];
[viewController updateProgressBar:currentProgress]

from my EventsManager class, updateProgressBar is called (proven with breakpoints), but the progress bar update is ignored. No errors or exceptions thrown. and updateProgressBar called. is displayed in the console.

What you can do is add an NSNotification for the progress bar update and call it from anywhere you want..

In your viewDidLoad of ViewController add this observer

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

Then add the following method

-(void)progressBarUpdater:(float)currentProgress
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"progressBarUpdater" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:currentProgress,@"progress", nil]];
}

and Update your method

- (void)updateProgressBar:(NSNotification *)notificaiton
{
    NSLog(@"updateProgressBar called.");
    NSDictionary *dict = [notificaiton userInfo];
    progressBar.progress = [dict valueForKey:@"progress"];

    //  progressBar.progress = myProgress;
}

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