[英]how to change a UILabel of a UIViewController from another UIViewController
[英]Objective C - How to change image from another class (another UIViewController)
我正在使用NSObject
類來處理一些服務器方法。
其中一種方法是從DB(parse.com)下載圖像。
問題在於,顯示圖像的UIViewController
加載速度比下載過程(圖像始終為nil
)要快,並且在將圖像放入設備后僅2秒。
如何從NSObject
類(帶有下載方法的類)更新UIImageView
圖像(userProfile類)?
UIViewController
在UITabBar
我知道如何檢測下載過程的結束,但是我不知道如何從另一個類訪問UIImageView屬性。
使用delegate
來滿足您的要求。 檢查實現委托或ios_delegates如何完成。
以下是一些理解:
說你在NSObject類中有委托方法來處理一些服務器方法
@protocol YouNSObjectClassDelegate <NSObject>
@required
-(void)imageDownloaded:(UIImage*)image;
@end
加
@property (nonatomic,strong) id<YouNSObjectClassDelegate> delegate;
在分配對象的任何viewcontroller時,不要忘記初始化委托
yourNSObjectClassObject.delegate = self;
在NSObject類中下載圖像時
if ([delegate respondsToSelector:@selector(imageDownloaded:)]) {
[delegate imageDownloaded:image];
}
在你想要有圖像的UIViewController中添加這些方法
-(void)imageDownloaded:(UIImage*)image
{
//Set Image here
}
當您調用NSObject Class
只需將UIImageView
傳遞給其他參數,下載圖像時,只需將新圖像設置為UIImageView
。 我猜您正在使用線程概念,因此僅在Main Thread
上更新UIImageView
。 您可以使用
dispatch_async(dispatch_get_main_queue(), ^(void){
//Set your Image to UIImageView
});
或使用
[self performSelectorOnMainThread:@selector(updateImage:) withObject:objects waitUntilDone:YES];
或者更好的是,您可以編寫自己的block
或delegate
方法,並在下載圖像時傳遞下載的圖像。
在tableView的cellForRowAtIndexPath
方法中,而不是直接設置圖像,而是使用GCD異步和完成塊。
在下載類標題中,聲明一個帶有完成塊的新方法:
- (void)downloadImagesWithCompletion:(void (^)(void))completion;
並執行:
- (void)downloadImagesWithCompletion:(void (^)(void))completion {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, NO), ^(void){
// Run your downloading here, and once your operation is complete...
dispatch_async(dispatch_get_main_queue(), ^(void){
completion();
});
});
}
在視圖控制器的處理方法中,如下調用:
[downloader downloadImagesWithCompletion:^(void) {
{
// your downloader is now complete, run your UI updates
}];
注意:此示例在完成塊中不包含任何返回值,但是您也可以輕松地做到這一點 。
您最好考慮一下,因為UIViewController是老板。 這意味着UIViewController開始下載圖像,處理完成並設置Tabbar圖像。 下載映像過程的類別只是一個工作者。 工人將老板委派給重要的決定。
下載圖像處理類試圖直接設置Tabbar圖像不是一個好主意。 將類設計為具有委托協議或阻止功能以告知“某人”完成圖像下載是一個好主意。
您最好使用SDWebImage庫。 圖書館的設計就像我說的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.