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 ...
随机推荐
- Linux统计文件夹下文件信息
统计当前文件夹里面有多少文件,即统计文件个数 ls -l |grep "^-"|wc -l 统计当前文件夹里面有多少文件夹,即统计文件夹个数 ls -l |grep "^ ...
- PHP学习笔记-00
PHP这门语言的就不用多说啦,使用率非常高的一门后端开发语言.之前一直希望可以学习了解一下PHP.之前主要在做Java和OC这类语言的开发,对于PHP这种脚本语言(动态语言)还是了解甚少. 近期看了一 ...
- .NET DataTable转化为json格式
标准的json用“分隔,不用' public static string DataSetToJson(DataTable dt) { string json = string.Empty ...
- [R] Draw a wordcloud
# 加载rJava.Rwordseg库 library(rJava); library(Rwordseg); library(RColorBrewer); # == 读入数据 lecture=read ...
- Linux块设备驱动 --块驱动相关的结构体及相关操作
http://blog.chinaunix.net/uid-23399063-id-70124.html
- hdu2047.java递推题
阿牛的EOF牛肉串 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total S ...
- android检查自动升级
好像大半年没发点啥了,也不知道自己瞎忙啥,闲下来发给最近的东东<安卓在线升级> 类已经封装好了,简单的调用就OK了.这里的数据交互,我是用.NET写的一个webservice来交互.废话也 ...
- mysql锁表和解锁语句分享
对于MySQL来说,有三种锁的级别:页级.表级.行级 页级的典型代表引擎为BDB. 表级的典型代表引擎为MyISAM,MEMORY以及很久以前的ISAM. 行级的典型代表引擎为INNODB. ...
- Spring中 bean定义的parent属性机制的实现分析
在XML中配置bean元素的时候,我们常常要用到parent属性,这个用起来很方便就可以让一个bean获得parent的所有属性 在spring中,这种机制是如何实现的? 对于这种情况 tra ...
- windows下安装wamp和wordpress
安装wamp WAMP是一个windows上的php开发集成环境,一键安装php,apache和mysql,非常方便. 双击wampserver2.2exxxxxxxxxx.exe文件进行安装,安装过 ...