【问题标题】:Alter UIView elements outside viewDidLoad改变 viewDidLoad 之外的 UIView 元素
【发布时间】:2013-10-23 14:19:59
【问题描述】:

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

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

我有什么遗漏的吗?

超级简单的例子:

这行得通

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

这没有(这个方法在我的视图控制器中)

- (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 called. 会显示在控制台中。

【问题讨论】:

  • 您能否提供代码 sn-ps 来说明问题?很难回答这样一个通用的场景。原则上,您应该能够从 viewDidLoad 以外的地方更新您的视图,但这一切都取决于您的设计。请提供更清晰的说明。
  • 添加示例。这是非常基本的。我的设计并不复杂或原创。这是一个包含几个 UIView 元素的基本视图。
  • 代码乍一看还不错..我希望这不是您拥有的确切代码-因为在这两种情况下,您的progressBar.progress都是0.7,这意味着即使执行了updateProgressBar, progressBar 不会显示任何进度。您能否确认不是这种情况?
  • 不,事实并非如此。我试图让我的例子尽可能简短。再次更新示例。
  • 我认为问题可能是您的 ViewController 的两个不同实例在这里运行。我还不知道你的实现——但是当你想将 progressBar 进度从 0.5 更改为 1.0 时,你能确认已经创建了一个 viewController 实例吗?理想情况下,如果 viewController 已经创建并且 EventsManager 正在尝试基于某些业务逻辑更新 viewController 的 progressBar,它可以向 viewController 发送通知以将其进度条更新为 EventsManager 可以提供的所需值。

标签: ios objective-c xcode


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多