[英]I want to add MBProgressHUD in NSObject class
我正在從我的NSObject類在服務器上上傳數據,現在我想在上傳數據時顯示MBProgressHUD,我知道如何使用ViewController顯示MBProgressHUD,但不知道如何通過NSObject類顯示。
AppDelegate* delegate = [[UIApplication sharedApplication] delegate];
[delegate.window addSubview:HUD];
...
[HUD removeFromSuperview];
有幾種解決此類問題的方法。 盡管可以使用塊,KVO或通知,但是最常見的一種是使用委托模式。
您應該首先創建一個協議,以便可以在UIViewController
和進行調用的NSObject
之間進行通信。 盡管您不需要創建該通信,但應該使用它來獲得更靈活的代碼。
通常,我會這樣做:
@protocol CommunicationDelegate <NSObject>
@required
-(void)communicationSucceed;
-(void)communicationFailedWithError:(NSError*)anError;
在您的NSObject
內部,對於符合協議CommunicationDelegate
的對象,您將擁有weak
引用。 在您的.h文件中,您應具有以下內容:
@property(nonatomic, weak) id <CommunicationDelegate> communicationDelegate;
在實際開始使用NSObject
,您應該執行以下操作:
myObjectThatWillDoSomething.communicationDelegate = self;
目前,您的UIViewController
和NSObject
之間具有有效的引用。 在您的UIViewController的.h文件中,添加以下內容:
@interface myViewController : UIViewController <CommunicationDelegate>
因此,您的UIViewController
符合CommunicationDelegate
協議。
現在,您可以從UIViewController
啟動MBProgressHUD
。 NSObject
完成工作后,您可以調用:
[communicationDelegate communicationSucceed];
要么
[communicationDelegate communicationFailedWithError:anError]; //anError is used to describe what went wrong
一旦調用了這些方法之一,就可以刪除MBProgressHUD
。 了解此方法在UIViewController
內部調用。
當您上傳NSObject時,會顯示一個視圖,對嗎? 因此,在該視圖中顯示HUD。 您可能需要創建一個委托,以在下載開始,結束時以及出現錯誤時通知視圖。
使用NSNotification Center停止指示器,在視圖控制器中用監聽方法聲明NSNotification。 並從Webservice文件中發布通知。 通知中心監聽方法中的停止指示器。
此鏈接將為您提供幫助
在您的上傳器對象上創建委托協議
@protocol UploaderThingyDelegate <NSObject>
-(void)stuffStarted;
-(void)stuffEnded;
@end
@interface UploaderThingy : NSObject
@property (weak) id<UploaderThingyDelegate> delegate;
將相關的View或ViewController設置為上載者委托,並觸發MBProgressHUD在此處添加/刪除。
這些下面的代碼在NSObject文件中工作正常
步驟1:下載 https://github.com/jdg/MBProgressHUD
步驟2:添加代理MBProgressHUDDelegate
步驟3:聲明實例MBProgressHUD * HUD;
步驟4:在需要的地方編寫代碼:
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[[UIApplication sharedApplication].keyWindow addSubview:HUD];
HUD.delegate = self;
HUD.labelText = @"Processing";
[HUD show:YES];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.