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 ...
随机推荐
- 驱动lx4f120h,头文件配置,没有完全吃透,望指点
来了块开发板,没接触过,希望能驱动起来,就首先试一下驱动LED,没想到刚开始建好工程问题就来了 使用GPIO驱动,首先想到的是关于GPIO的头文件gpio.h,事实上这个还不够,还需要设置一下系统的配 ...
- leetCode 53.Maximum Subarray (子数组的最大和) 解题思路方法
Maximum Subarray Find the contiguous subarray within an array (containing at least one number) whic ...
- HDU ACM 1392 Surround the Trees->凸包
分析:直接求出凸包.再算边长就可以. 另外仅仅有一个点时为0.00单独处理,两个点直接为距离也单独处理. #include<iostream> #include<cmath> ...
- linux 安装软件的地方
用下边这个命令:mysqladmin -u root -p variables root是你的数据库帐号回车后会提示你输入密码,输入上边填写的帐号对应的密码 回车后出来一个大表,找到datadir这一 ...
- 手动创建Servlet--J2EE学习笔记
Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层. 使用 Serv ...
- 获取IMEI码
核心代码: Imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId(); 1.加入权限 在manifes ...
- Java基础知识强化之集合框架笔记59:Map集合之TreeMap(TreeMap<String,String>)的案例
1. TreeMap类的概述: 键是红黑树结构,可以保证键的排序和唯一性. 2. TreeMap案例: TreeMap<String, String> 代码示例: package cn.i ...
- CentOS7上GitLab的使用
生成SSH Keys 生成root账号的ssh key # ssh-keygen -t rsa -C "admin@example.com" 显示pub key的值 # cat ~ ...
- RedHat7上安装PHP
编译安装PHP 下载PHP# wget http://cn2.php.net/distributions/php-7.0.0.tar.gz 解压缩PHP# tar -zxvf php-7.0.0.ta ...
- extSourceStat_7Day_Orders.php
<?php /** Log文件格式2012/7/4 列号 字段含义 取值 ------------------------------------------------------------ ...