ViewController.m
#import "ViewController.h"
#import "UIImageView+WebImage.h"
@interface ViewController ()
//连线.. 在storyboard 创建一个imageView
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//图片地址
[_imgView setImageWithUrl:@"http://banbao.chazidian.com/uploadfile/2016-01-25/s145368924044608.jpg"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
UIImageView+WebImage.h
#import <UIKit/UIKit.h>
@interface UIImageView (WebImage)
-(void)setImageWithUrl:(NSString *)url;
@end
UIImageView+WebImage.m
#import "UIImageView+WebImage.h"
@implementation UIImageView (WebImage)
//根据url设置图片
-(void)setImageWithUrl:(NSString *)url
{
//第一步:创建子线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage:) object:url];
[thread start];
}
//获取图片数据
-(void)loadImage:(NSString *)url
{
//第二步:根据url获取图片数据
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
if (imgData) {
UIImage *image = [[UIImage alloc] initWithData:imgData];
///第三步:回到主线程更改图片属性
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:nil];
}
}
@end