iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView
在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 = ;
[self.view addSubview:self.imageView];
[self.imageView setTranslatesAutoresizingMaskIntoConstraints: NO]; //创建前一张按钮
UIButton *prevButton = [[UIButton alloc] init];
prevButton.frame = CGRectMake(, , , );
[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(, , , );
[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:@, @"VDist", @, @"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: metrics:metrics views:views]];
[contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[prevButton]-(>=0)-[nextButton(==prevButton)]-Padding-|" options: metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-Padding-[imageView]-Padding-|" options: metrics:metrics views:views]];
[contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-VDist-[header]-Padding-[imageView]-(>=VDist)-|" options: metrics:metrics views:views]];
//垂直居中
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:prevButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier: constant:]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:nextButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier: constant:]]; [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;
} @end
4. 运行
iOS: 学习笔记, 使用performSelectorOnMainThread及时刷新UIImageView的更多相关文章
- iOS学习笔记-精华整理
iOS学习笔记总结整理 一.内存管理情况 1- autorelease,当用户的代码在持续运行时,自动释放池是不会被销毁的,这段时间内用户可以安全地使用自动释放的对象.当用户的代码运行告一段 落,开始 ...
- iOS学习笔记总结整理
来源:http://mobile.51cto.com/iphone-386851_all.htm 学习IOS开发这对于一个初学者来说,是一件非常挠头的事情.其实学习IOS开发无外乎平时的积累与总结.下 ...
- [置顶] iOS学习笔记47——图片异步加载之EGOImageLoading
上次在<iOS学习笔记46——图片异步加载之SDWebImage>中介绍过一个开源的图片异步加载库,今天来介绍另外一个功能类似的EGOImageLoading,看名字知道,之前的一篇学习笔 ...
- IOS学习笔记48--一些常见的IOS知识点+面试题
IOS学习笔记48--一些常见的IOS知识点+面试题 1.堆和栈什么区别? 答:管理方式:对于栈来讲,是由编译器自动管理,无需我们手工控制:对于堆来说,释放工作由程序员控制,容易产生memor ...
- iOS学习笔记之UITableViewController&UITableView
iOS学习笔记之UITableViewController&UITableView 写在前面 上个月末到现在一直都在忙实验室的事情,与导师讨论之后,发现目前在实验室完成的工作还不足以写成毕业论 ...
- iOS学习笔记31-从图册获取图片和视频
一.从图册中获取本地图片和视频 从图册中获取文件,我们使用的是UIImagePickerController,这个类我们在之前的摄像头中使用过,这里是链接:iOS学习笔记27-摄像头,这里我们使用的是 ...
- iOS学习笔记20-地图(二)MapKit框架
一.地图开发介绍 从iOS6.0开始地图数据不再由谷歌驱动,而是改用自家地图,当然在国内它的数据是由高德地图提供的. 在iOS中进行地图开发主要有三种方式: 利用MapKit框架进行地图开发,利用这种 ...
- iOS学习笔记——AutoLayout的约束
iOS学习笔记——AutoLayout约束 之前在开发iOS app时一直以为苹果的布局是绝对布局,在IB中拖拉控件运行或者直接使用代码去调整控件都会发上一些不尽人意的结果,后来发现iOS在引入了Au ...
- IOS学习笔记25—HTTP操作之ASIHTTPRequest
IOS学习笔记25—HTTP操作之ASIHTTPRequest 分类: iOS2012-08-12 10:04 7734人阅读 评论(3) 收藏 举报 iosios5网络wrapper框架新浪微博 A ...
随机推荐
- 圣诞节来了,雪花纷飞的CSS3动画,还不首页用起来
圣诞节来了,冬天来了,怎么可以没有雪花纷飞效果,昨天下班前折腾了一会儿,弄了个雪花纷飞的实例,有兴趣的可以交流分享下. 原文链接:http://www.html5think.com/article/i ...
- 【剑指Offer学习】【面试题40:数组中仅仅出现一次的数字】
题目:一个整型数组里除了两个数字之外.其它的数字都出现了两次,请敲代码找出这两个仅仅出现一次的数字. 要求时间复杂度是O(n),空间复杂度是O(1). 举例说明 比如输入数组{2, 4, 3, 6, ...
- malloc()与calloc差别
Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slig ...
- Java的finally理解
1.为什么要用finally 先看一个没有finally的异常处理try-catch语句: 如果count为要使用到的资源,而且用完要求释放此资源.那么我们能够把释放资源的语句放到try-catch后 ...
- 仿path菜单button的实现
path刚出来时.其菜单button也算是让大多数人感到了惊艳,如今看来事实上是非常easy的就是动画的结合. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQ ...
- Windows环境下tomcat配置日志输出
在Linux系统中,可以通过tail -f catalina.out 来跟踪Tomcat 和相关应用运行的情况. 在windows下,catalina日志与Linux记录的内容有很大区别,大多信息 ...
- 晕,hibernate 的 merge和cascade="all-delete-orphan"要慎重合在一起使用
遇到一个比较后悔莫及事情,使用了hibernate 的 merge和cascade="all-delete-orphan" ,子表数据被删除了. 1.使用cascade=" ...
- AWVS介绍
使用AWVS对域名进行全局分析,深入探索: 首先,介绍一下AWVS这个工具. Acunetix Web Vulnerability Scanner(简称AWVS)是一款知名的网络漏洞扫描工具,它通过网 ...
- Ⅱ.AngularJS的点点滴滴--缓存
模板缓存-$templateCache and 缓存工厂 $cacheFactory 1.使用script标签 <html ng-app> <script src="htt ...
- Linux重复执行上一条命令
执行刚刚执行的一条命令: !! 执行最近一个以指定字符串开头的命令(比如man) !man !m 引用上一个命令的最后一个参数 !$ <ESC>, .