简体   繁体   English

在viewDidLoad之外更改UIView元素

[英]Alter UIView elements outside viewDidLoad

I have an EventsManager class that communicates with my view controller. 我有一个与我的视图控制器通信的EventsManager类。 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. 我希望能够通过从EventManager类中调用视图内部的方法(例如,诸如updateProgressBar)来更新UIView元素(图像,进度条等)。

However, anytime I try to update UIView elements from within any method in my view other than viewDidLoad , it's just ignored entirely. 但是,无论何时我尝试从视图中除viewDidLoad之外的任何方法中更新UIView元素时,都将被完全忽略。

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. 从我的事件管理类, updateProgressBar 称为(断点证实),但进度条更新被忽略。 No errors or exceptions thrown. 没有引发错误或异常。 and updateProgressBar called. 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.. 您可以做的是为进度条更新添加一个NSNotification,然后从任意位置调用它。

In your viewDidLoad of ViewController add this observer 在您的ViewControllerviewDidLoad中添加此观察者

[[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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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