MPProgressHUD是一个非常好用的进度指示器类库,其提供了苹果官方sdk没有提供的progress indicator接口,且提供多种样式,使用方法简便。
首先将类库文件添加到项目中。
使用实例代码如下:
[cpp] view
plaincopy
- #import <UIKit/UIKit.h>
- #import "MBProgressHUD.h"
[cpp] view
plaincopy
- #import <libkern/OSAtomic.h>
- @interface SampleViewController : UITableViewController <MBProgressHUDDelegate>
- @property (nonatomic, retain) NSCondition* condition;
- @property (nonatomic, retain) MBProgressHUD* hud;
- @end
- static volatile NSInteger WAITING_RESPONSE_FOR_SERVERRESPONSE = 0;
- - (void) popOutMBProgressHUD;
- - (void) selectorForMPProgressHUD;
- - (void) notifyMPProgressHUDToDisappear;
- @implementation SampleViewController
- @synthesize hud = _hud;
- @synthesize condition = _condition;
- - (id) initWithCoder:(NSCoder *)aDecoder
- {
- self = [super initWithCoder: aDecoder];
- if (self != nil) {
- _hud = nil;
- _condition = [[NSCondition alloc] init];
- }
- return self;
- }
- - (void) dealloc
- {
- [_hud release];
- [_condition release];
- }
- - (void) popOutMBProgressHUD
- {
- MBProgressHUD* tempHud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
- self.hud = tempHud;
- [self.navigationController.view addSubview: tempHud];
- self.hud.dimBackground = YES;
- self.hud.delegate = self;
- self.hud.labelText = @"正在处理";
- [self.hud showWhileExecuting:@selector(selectorForMPProgressHUD) onTarget:self withObject: nil animated:YES];
- [tempHud release];
- }
- - (void) selectorForMPProgressHUD
- {
- OSAtomicCompareAndSwapInt(0,
- 1,
- &WAITING_RESPONSE_FOR_SERVERRESPONSE);
- [self performSelectorInBackground: @selector(tempSelector) withObject: nil];
- [self.condition lock];
- while (OSAtomicCompareAndSwapInt(1,
- 1,
- &WAITING_RESPONSE_FOR_SERVERRESPONSE)) {
- NSDate* timeOutDate = [NSDate dateWithTimeIntervalSinceNow: 5.0f];
- [self.condition waitUntilDate: timeOutDate];
- }
- [self.condition unlock];
- }
- - (void) notifyMPProgressHUDToDisappear
- {
- //通知进度显示hud消失
- [self.condition lock];
- OSAtomicCompareAndSwapInt(1,
- 0,
- &WAITING_RESPONSE_FOR_SERVERRESPONSE);
- [self.condition signal];
- [self.condition unlock];
- }
[cpp] view
plaincopy
- - (void)hudWasHidden:(MBProgressHUD *)hud
- {
- // Remove HUD from screen when the HUD was hidded
- [self.hud removeFromSuperview];
- self.hud = nil;
- }
- - (void) tempSelector
- {
- sleep(3.0f);//模拟真实的耗时操作
- [self notifyMPProgressHUDToDisappear];
- }
- @end
时间: 2024-10-08 04:52:05