在iOS中, 界面刷新在主线程中进行, 这导致NSURLSession远程下载图片使用UIImageView直接设置Image并不能及时刷新界面.
下面的代码演示了如何使用 performSelectorOnMainThread: withObject: waitUntilDone: 方法来及时刷新图片
1. 创建iOS空应用程序(Empty Application).
2. 加入一个控制器类. 在YYAppDelegate.m中修改
#import "MainViewController.h" @implementation YYAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[MainViewController alloc] initWithNibName:nil bundle:nil]; [self.window makeKeyAndVisible]; return YES; }3. 修改MainViewController.m文件
// // MainViewController.m // UIByCodeDemo0602_ImageView // // Created by yao_yu on 14-6-3. // Copyright (c) 2014年 yao_yu. All rights reserved. // #import "MainViewController.h" @interface MainViewController () @property(nonatomic, strong)UILabel *header; @property(nonatomic, strong)UIImageView *imageView; @property(nonatomic, strong)UIImage *imagedata; @end @implementation MainViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; self.imagedata = nil; //创建标题标签 self.header = [[UILabel alloc] init]; self.header.text = @"示意图"; self.header.textAlignment = NSTextAlignmentCenter; [self.view addSubview: self.header]; [self.header setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建图片视图 self.imageView = [[UIImageView alloc] init]; [self.imageView setBackgroundColor: [UIColor blueColor]]; [self.imageView setImage: [UIImage imageWithContentsOfFile:@"/Users/yao_yu/Documents/aaa/3002302_.png"]]; self.imageView.layer.cornerRadius = 10; [self.view addSubview:self.imageView]; [self.imageView setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建前一张按钮 UIButton *prevButton = [[UIButton alloc] init]; prevButton.frame = CGRectMake(0, 20, 300, 20); [prevButton setBackgroundColor:[UIColor redColor]]; [prevButton setTitle:@"前一张" forState:UIControlStateNormal]; [prevButton addTarget:self action:@selector(onShowPrevImage:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview: prevButton]; [prevButton setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建后一张按钮 UIButton *nextButton = [[UIButton alloc] init]; nextButton.frame = CGRectMake(0, 20, 300, 20); [nextButton setBackgroundColor:[UIColor redColor]]; [nextButton setTitle:@"后一张" forState:UIControlStateNormal]; [nextButton addTarget:self action:@selector(onShowNextImage:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview: nextButton]; [nextButton setTranslatesAutoresizingMaskIntoConstraints: NO]; //约束 NSMutableArray *contraits = [NSMutableArray array]; NSDictionary *metrics = [NSDictionary dictionaryWithObjectsAndKeys:@20, @"VDist", @5, @"Padding", nil]; UILabel *header = self.header; UIImageView *imageView = self.imageView; NSDictionary *views = NSDictionaryOfVariableBindings(header, imageView, prevButton, nextButton); [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[header]-Padding-|" options:0 metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[prevButton]-(>=0)-[nextButton(==prevButton)]-Padding-|" options:0 metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[imageView]-Padding-|" options:0 metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-VDist-[header]-Padding-[imageView]-(>=VDist)-|" options:0 metrics:metrics views:views]]; //垂直居中 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:prevButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:nextButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]]; [self.view addConstraints:contraits]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } -(void)onShowPrevImage:(id)sender { NSURL *URL = [NSURL URLWithString:@"http://img.gtimg.cn/images/hq_parts/hushen/stocks/300230.png"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { self.imageView.image = nil; self.imagedata = [UIImage imageWithData:data]; [self performSelectorOnMainThread:@selector(updateMyImage) withObject:nil waitUntilDone:NO]; }]; [task resume]; } -(void)onShowNextImage:(id)sender { NSURL *URL = [NSURL URLWithString:@"http://img.gtimg.cn/images/hq_parts/hushen/stocks/300023.png"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { self.imageView.image = nil; self.imagedata = [UIImage imageWithData:data]; [self performSelectorOnMainThread:@selector(updateMyImage) withObject:nil waitUntilDone:NO]; }]; [task resume]; } - (void)updateMyImage { if (!self.imageView.image) self.imageView.image = self.imagedata; return; } @end4. 运行
iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView,布布扣,bubuko.com
iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView
原文:http://blog.csdn.net/yao_yu_126/article/details/28872139