这个实例主要实现了隔相同的时间一张张加载图片在用for循环创建6个不同的图片视图上,且点击屏幕可使未完成的进程被取消,并退出即未加载的图片停止加载,有兴趣的朋友可以一试。(相应的注意点都已经在代码中注释)
#import "ViewController.h"
#define kUrl @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/s38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resMode=bicub&op_usm=0.5,0.5,0,0&iccEmbed=0&layer=comp&.v=1454777389943"
@interface ViewController (){
int tagValue;
UIImage *image;
NSMutableArray *threadArray;
}
@end
@implementation ViewController
-(void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
tagValue = 100;
threadArray = [NSMutableArray array];
self.edgesForExtendedLayout = 0;
self.title = @"多张图片";
[self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:24],NSForegroundColorAttributeName:[UIColor greenColor]}];
// 创建多个UIimageview
for (int row = 0; row<3; row++) {
for (int list = 0; list<2; list++) {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10+list*200, 10+row*200, 200, 200)];
imageView.tag = tagValue++;
imageView.backgroundColor = [UIColor redColor];
imageView.userInteractionEnabled = YES;
[self.view addSubview:imageView];
}
}
// 创建多个子线程
for (int index = 0; index<6; index++) {
[NSThread detachNewThreadSelector:@selector(thread:) toTarget:self withObject:@(index)];
}
}
// 通过url加载网络图片
- (void)thread:(NSNumber *)index{
[threadArray addObject:[NSThread currentThread]];
NSThread *thread = [NSThread currentThread];
[NSThread sleepForTimeInterval:[index intValue]];//通过线程休眠实现顺序加载
if (thread.isCancelled == YES) {
[NSThread exit];
}
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kUrl]];
image = [UIImage imageWithData:data];
// ❤️❤️回到主线程
[self performSelectorOnMainThread:@selector(updateUI:) withObject:index waitUntilDone:YES];
}
// 更新UI
- (void)updateUI:(NSNumber *)index{
UIImageView *imageV = [self.view viewWithTag:[index integerValue]+100];
imageV.image = image;
}
//点击屏幕取消未完成的线程
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%@",threadArray);
for (int index = 0; index<6; index++) {
NSThread *thread = threadArray[index];
if (thread.isFinished == NO) {
[thread cancel];//取消不是退出
}
}
}
@end