iOS 开发之 为UIButton添加类别方法加载网络图片
2016-04-29 11:30
1026 查看
UIButton+WebCache.h
#import <UIKit/UIKit.h>
// 为Button添加类别方法
@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
#import <UIKit/UIKit.h>
// 为Button添加类别方法
@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
相关文章推荐
- 王高利:udp/tcp协议及三次四次握手
- MaterialDesign学习项目
- iOS适配http和Url scheme
- tcp/ip协议,http协议详解
- NSUrlRequest想使用post上传多字段多图片的httpbody写法
- http请求中java中的302和sendRedirect的区别
- HTTP各个状态返回值
- bzoj 1834: [ZJOI2010]network 网络扩容(isap+费用流)
- UDP 网络通信 C#
- UDP SOCKET网络通信 C#
- HTTP权威指南读书笔记(一)HTTP概述、URL和资源及报文详解
- IOS SCNetworkReachability和Reachability监测网络连接状态
- IOS安装包分发(windows+tomcat+私有证书https)
- Ambiguous handler methods mapped for HTTP path
- 4月全球域名商新增注册量21强:厦门点媒网络上榜
- HTTP head 详解 (转)
- 常见的网络设备
- 深度卷积网络CNN与图像语义分割
- http服务跟踪及调试工具
- Android中检测手机制式和移动网络类型