创建
UIImageView的类别
UIImageView+webCach.h
#import <UIKit/UIKit.h>
@interface UIImageView (webCach)
-(void)setImageUrl:(NSURL *)url;
@end
#import "UIImageView+webCach.h"
@implementation UIImageView (webCach)
-(void)setImageUrl:(NSURL *)url
{
dispatch_queue_t queue=dispatch_queue_create("loafImage", NULL);
//异步线程
dispatch_async(queue, ^{
NSData *data=[NSData dataWithContentsOfURL:url];
UIImage *image=[UIImage imageWithData:data];
//让主线程去做
dispatch_sync(dispatch_get_main_queue(), ^{
self.image=image;
});
});
}
@end
#import "MyAppDelegate.h"
#import "UIImageView+webCach.m"
@implementation MyAppDelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
count=1;
//异步加载图片
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(60, 20, 200, 120)];
imageView.backgroundColor=[UIColor greenColor];
[imageView setImageUrl:[NSURL URLWithString:@"http://news.imust.cn/UploadFiles/2013/2/2013111815315038005.jpg"]];
UIImageView *imageView2=[[UIImageView alloc]initWithFrame:CGRectMake(60, 180, 200, 120)];
imageView2.backgroundColor=[UIColor greenColor];
[imageView2 setImageUrl:[NSURL URLWithString:@"http://news.imust.cn/UploadFiles/2013/2/2013111815315038005.jpg"]];
[self.window addSubview:imageView];
[self.window addSubview:imageView2];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"按钮" forState:UIControlStateNormal];
button.frame=CGRectMake(110,320 , 100, 40);
[button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:button];
return YES;
}
-(void)btnAction:(UIButton *)sender
{
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(count*10, 370, 200, 120)];
imageView.backgroundColor=[UIColor greenColor];
[imageView setImageUrl:[NSURL URLWithString:@"http://news.imust.cn/UploadFiles/2013/2/2013111815315038005.jpg"]];
[self.window addSubview:imageView];
count++;
//按钮不可用...
sender.enabled=NO;
}