UIButton 加載網絡圖片


 

以后就可以 用這個分類   UIButton輕松加載網絡圖片了,

UIButton+WebCache.h

#import <UIKit/UIKit.h>

@interface UIButton (WebCache)
- (void)xr_setButtonImageWithUrl:(NSString *)urlStr;  
@end

 

UIButton+WebCache.m

#import "UIButton+WebCache.h"

@implementation UIButton (WebCache)
- (void)xr_setButtonImageWithUrl:(NSString *)urlStr {
    
    NSURL * url = [NSURL URLWithString:urlStr];
    // 根據圖片的url下載圖片數據
    dispatch_queue_t xrQueue = dispatch_queue_create("loadImage", NULL); // 創建GCD線程隊列
    dispatch_async(xrQueue, ^{
        // 異步下載圖片
        UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        // 主線程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setImage:img forState:UIControlStateNormal];
        });
    });  
    
}  

@end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM