在开发的过程中,一开始想加一个系统的loading条,可是当时由于犯懒就直接做了资源,今儿瞅见这篇文章觉得有必要记录一下
首先是在UIAlertView里显示进度条:
- UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:@"Title"
- message:@"Message"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil]
- autorelease];
- [alertView show];
如果要添加一个进度条,只要先创建并设置好一个UIProgressView的实例,再利用addSubbiew方法添加到alertView中即可。
在实际应用中,我可能需要在类中保存进度条的对象实例,以便更新其状态,因此先在自己的ViewController类中添加成员变量:
- // MySampleViewController.h
- #import <UIKit/UIKit.h>
- @interface MySampleViewController : UIViewController {
- @private
- UIProgressView* progressView_;
- }
- @end
接下来写一个叫做showProgressAlert的方法来创建并显示带有进度条的alert窗口,其中高亮的部分就是把进度条添加到alertView中:
- - (void)showProgressAlert:(NSString*)title withMessage:(NSString*)message {
- UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:title
- message:message
- delegate:nil
- cancelButtonTitle:nil
- otherButtonTitles:nil]
- autorelease];
- progressView_ = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
- progressView_.frame = CGRectMake(30, 80, 225, 30);
- [alertView addSubview:progressView_];
- [alertView show];
- }
为了让数据处理的子进程能够方便地修改进度条的值,再添加一个简单的方法:
- - (void)updateProgress:(NSNumber*)progress {
- progressView_.progress = [progress floatValue];
- }
- - (void)dismissProgressAlert {
- if (progressView_ == nil) {
- return;
- }
- if ([progressView_.superview isKindOfClass:[UIAlertView class]]) {
- UIAlertView* alertView = (UIAlertView*)progressView_.superview;
- [alertView dismissWithClickedButtonIndex:0 animated:NO];
- }
- [progressView_ release];
- progressView_ = nil;
- }
假设处理数据的方法叫processData,当然它会在一个单独的线程中运行,下面的片段示意了如何更新进度条状态,以及最后如何让它消失。
- - (void)processData:(int)total {
- for (int i = 0; i < total; ++i) {
- // Update UI to show progess.
- float progress = (float)i / total;
- NSNumber* progressNumber = [NSNumber numberWithFloat:progress];
- [self performSelectorOnMainThread:@selector(updateProgress:)
- withObject:progressNumber
- waitUntilDone:NO];
- // Process.
- // do it.
- }
- // Finished.
- [self performSelectorOnMainThread:@selector(dismissProgressAlert)
- withObject:nil
- waitUntilDone:YES];
- // Other finalizations.
- }
最后的效果是这样的
![](http://hi.csdn.net/attachment/201203/11/0_1331435648Tg4U.gif)
原文UIAlertView显示进度条原文地址: http://www.gocalf.com/blog/iphone-dev-progressview-in-alertview.html