简体   繁体   English

从后台更新 UIProgressView

[英]Update UIProgressView from background

I have a tab bar application with three tabs.我有一个带有三个标签的标签栏应用程序。 In my second tab view i have a UIProgressView .在我的第二个标签视图中,我有一个UIProgressView I have a NSTimer in my viewDidLoad method which calls a method which updates the progressView我的viewDidLoad方法中有一个 NSTimer,它调用了一个更新 progressView 的方法

progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];

All is fine so far.到目前为止一切都很好。

I want to know how do i run the timer in the background throughout the lifecycle of the app, so that progressView is updated no matter which view the user is in. It will be great if you can show me with a code snippet.我想知道如何在应用程序的整个生命周期中在后台运行计时器,以便无论用户在哪个视图中都会更新progressView 。如果您可以向我展示代码片段,那就太好了。

Thanks in advance.提前致谢。

It's not advisable to update UI elements from background threads.不建议从后台线程更新 UI 元素。 Also, it's not advisable to modify UI elements of a view when the user is not in that view.此外,当用户不在该视图中时,不建议修改该视图的 UI 元素。 You are using precious system resources.您正在使用宝贵的系统资源。

Better way is to update the ProgressBar as soon as that view becomes active...更好的方法是在该视图变为活动状态后立即更新 ProgressBar ...

UPDATE : You can see here to know how to run a task in background thread.更新:您可以在这里查看以了解如何在后台线程中运行任务。 You could set up your NSTimer to start in the selector you specify there.您可以将NSTimer设置为在您在那里指定的选择器中启动。 But again, this kind of stuff could lead to some weird bugs.但同样,这种东西可能会导致一些奇怪的错误。 Better to avoid..最好避免..

u can add the method in background this way你可以通过这种方式在后台添加方法

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Add code here to do background processing
// increment the progress here and keep the property of that count in appdelegate 
//
dispatch_async( dispatch_get_main_queue(), ^{
    // Add code here to update the UI/send notifications based on the
    // results of the background processing
});

}); });

in diffent view's viewWillAppear u can set this way: [loadingProgressView setProgress: appDelegate.count];在不同视图的 viewWillAppear 中,您可以这样设置: [loadingProgressView setProgress: appDelegate.count];

You could keep a property in the ProgressViewController (or even in the app delegate), say a float that tracks the progress.您可以在 ProgressViewController 中(甚至在应用程序委托中)保留一个属性,例如跟踪进度的float When you need to update the progress, another ViewController can change the value of the property.当您需要更新进度时,另一个 ViewController 可以更改该属性的值。

Once the view becomes visible, update the UI ( UIProgressView ) from viewWillAppear: .一旦视图变得可见,从viewWillAppear:更新 UI ( UIProgressView )。

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

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