首先創(chuàng)建一個(gè) "類目" 類名為"UIimageView" 類目名為"WebImage"
創(chuàng)建完成之后"UIImageView+WebImage"
創(chuàng)建"類目"方法:new file -> Objective-C File -> File Type選Category
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)
//根據(jù)url設(shè)置圖片
-(void)setImageWithUrl:(NSString *)url
{
//第一步:創(chuàng)建子線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage:) object:url];
[thread start];
}
//獲取圖片數(shù)據(jù)
-(void)loadImage:(NSString *)url
{
//第二步:根據(jù)url獲取圖片數(shù)據(jù)
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
在"Main.storyboard"文件中 拖一個(gè)"UIimageView"并將其拖動(dòng)到"ViewController.m" 文件
中當(dāng)做屬性
回到 "ViewController.m" 文件 調(diào)用 "UIImageView+WebImage.h" 文件
import "ViewController.h"
import "UIImageView+WebImage.h"
@interface ViewController ()
@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"];
}
@end