美文网首页
多线程 UIimageView加载图片

多线程 UIimageView加载图片

作者: 一枚小菜鸟 | 来源:发表于2016-05-03 20:09 被阅读153次

首先创建一个 "类目" 类名为"UIimageView" 类目名为"WebImage"
创建完成之后"UIImageView+WebImage"

创建"类目"方法: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)

//根据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


在"Main.storyboard"文件中 拖一个"UIimageView"并将其拖动到"ViewController.m" 文件
中当做属性

    回到 "ViewController.m" 文件 调用 "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

相关文章

网友评论

      本文标题:多线程 UIimageView加载图片

      本文链接:https://www.haomeiwen.com/subject/dphrrttx.html