ios - 在 viewDidLoad 之外更改 UIView 元素

标签 ios objective-c xcode

我有一个与我的 View Controller 通信的 EventsManager 类。我希望能够通过从 EventManager 类调用 View 内的方法(例如 updateProgressBar)来更新 UIView 元素(图像、进度条等)。

但是,每当我尝试从我 View 中的任何方法中更新 UIView 元素时,除了 viewDidLoad 之外,它都会被完全忽略。

有什么我遗漏的吗?

super 简单的例子:

这行得通

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

这不是(这个方法在我的 View Controller 中)

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

所以,如果我调用:

float currentProgress = 1.0;

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

在我的 EventsManager 类中,调用了 updateProgressBar (使用断点进行了验证),但进度条更新被忽略了。没有抛出错误或异常。并且调用了 updateProgressBar。 显示在控制台中。

最佳答案

你可以做的是为进度条更新添加一个 NSNotification 并从你想要的任何地方调用它..

在你的 ViewController 的 viewDidLoad 中添加这个观察者

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

然后添加如下方法

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

并更新你的方法

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

    //  progressBar.progress = myProgress;
}

关于ios - 在 viewDidLoad 之外更改 UIView 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532909/

相关文章:

View 出现后应用 iOS 8/XCode 6 自动布局约束

iphone - UIView 动画 block 不工作

ios - 可以让屏幕上的元素立即旋转

objective-c - 检测图像 iOS 中的黑色像素

ios - 如何检查 NSMutableSet 是否包含没有 nil 错误的元素

objective-c - 隐藏在 Lion 中的滚动条。如果人们不使用触控板,他们如何水平滚动?

ios - 如何从 xcode 项目中减小 ipa 的大小

ios - 使用 BGTaskScheduler 进行后台获取可以完美地与调试模拟配合使用,但在实践中却无法使用

ios - indexpath 行未准备好 segue 以进行详细信息披露

ios - 当用户从日历中选择日期时更新 UITableView