今天這個問題是,在一個iPhone程序中,我要在後臺作大量的數據處理,但願在界面上顯示一個進度條(Progress Bar)使得用戶瞭解處理進度。這個進度條應該是在一個模態的窗口中,使界面上其餘控件沒法被操做。怎麼用最簡單的方法來實現這個功能?UIAlertView是一個現成的模態窗口,若是能把進度條嵌入到它裏面就行了。 spa
如下內容適用於iOS 2.0+。 .net
咱們知道,若是要顯示一個alert窗口(好比用來顯示錯誤或警告信息、詢問用戶是否確認某操做等等),只要簡單地建立一個UIAlertView對象,再調用其show方法便可。示意代碼以下: 線程
1 2 3 4 5 6 7 orm |
UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [alertView show]; 對象 |
若是要添加一個進度條,只要先建立並設置好一個UIProgressView的實例,再利用addSubbiew方法添加到alertView中便可。 進程
在實際應用中,我可能須要在類中保存進度條的對象實例,以便更新其狀態,所以先在本身的ViewController類中添加成員變量: ci
1 2 3 4 5 6 7 8 9 get |
// MySampleViewController.h #import <UIKit/UIKit.h> @interface MySampleViewController : UIViewController { @private UIProgressView* progressView_; } @end it |
接下來寫一個叫作showProgressAlert的方法來建立並顯示帶有進度條的alert窗口,其中高亮的部分就是把進度條添加到alertView中: io
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
- (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]; } |
爲了讓數據處理的子進程可以方便地修改進度條的值,再添加一個簡單的方法:
1 2 3 |
- (void)updateProgress:(NSNumber*)progress { progressView_.progress = [progress floatValue]; } |
另外,數據處理完畢後,咱們還須要讓進度條以及alertView消失,因爲以前並無保存alertView的實例,能夠經過進度條的superview訪問之:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
- (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,固然它會在一個單獨的線程中運行,下面的片斷示意瞭如何更新進度條狀態,以及最後如何讓它消失。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
- (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. } |
在實際使用中,帶進度條的alert view大概長得是這樣的: