申明:此为本人学习笔记,若有纰漏错误之处的可留言共同探讨
/*
实现的效果
点击下载按钮,将图片从网络上下载下来。
思路
创建UIImageView,下载文件,开辟子线程,下载完回到主线程更新UI
注意点
数组记得初始化
*/
看看效果
#import "ViewController.h"
@interface ViewController () {
NSMutableArray *imageDataArray; // 图片
NSMutableArray *imageViewArray; // imageView
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
imageDataArray = [[NSMutableArray alloc]init];
imageViewArray = [[NSMutableArray alloc]init];
[self loadingUI];
}
#pragma mark - 更新UI
-(void)loadingUI {
// 按钮
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
downloadButton.frame = CGRectMake((self.view.frame.size.width-50)/2, self.view.frame.size.height/2, 100, 30);
downloadButton.backgroundColor = [UIColor blueColor];
[downloadButton setTitle:@"下载图片" forState:UIControlStateNormal];
[downloadButton addTarget:self action:@selector(downloadClick) forControlEvents:UIControlEventTouchDragInside];
[self.view addSubview:downloadButton];
// 15个UIImageView
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(55*(i+1), 55*(j+1), 50, 50)];
imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:imageView];
// UIActivityIndicatorView
UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicatorView.center = CGPointMake(25, 25);
indicatorView.tag = 100;
[indicatorView startAnimating];
[imageView addSubview:indicatorView];
[imageViewArray addObject:imageView];
}
}
}
#pragma mark - 按钮点击事件
-(void)downloadClick {
// 开辟新线程
[NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
}
#pragma mark -
-(void)downloadImage {
// 子线程内加载数据
for (int i = 0 ; i < 15 ; i++) {
NSString *urlString = [NSString stringWithFormat:@"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%d.jpg",i];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
[imageDataArray addObject:data];
// 加载数据完毕 跳回主线程
[self performSelectorOnMainThread:@selector(uploadImage:) withObject:@(i) waitUntilDone:NO];
}
}
-(void)uploadImage:(NSNumber*)index {
// 取出数据
NSInteger i = [index integerValue];
UIImageView *imageView = imageViewArray[i];
UIActivityIndicatorView *indicatorView =(UIActivityIndicatorView *)[imageView viewWithTag:100];
[indicatorView stopAnimating];
imageView.image = [UIImage imageWithData:imageDataArray[i]];
NSLog(@"取数据");
}
#pragma mark -
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end