在開發的過程中,一開始想加一個系統的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.
- }
最後的效果是這樣的
原文UIAlertView顯示進度條原文地址:http://www.gocalf.com/blog/iphone-dev-progressview-in-alertview.html