IOS: learning notes. Use javasmselecw.mainthread to promptly refresh UIImageView

Source: Internet
Author: User

In iOS, the interface is refreshed in the main thread, which causes NSURLSession to remotely download images and directly set the Image using UIImageView.

The following code demonstrates how to use javasmselecw.mainthread: withObject: waitUntilDone: Method to refresh images in a timely manner.

1. Create an Empty iOS Application ).

2. Add a controller class. modify it in 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. Modify the MainViewController. m file

//// 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) initWithNibNa Me :( NSString *) nibNameOrNil bundle :( NSBundle *) nibBundleOrNil {self = [super initWithNibName: nibNameOrNil bundle: role]; if (self) {// Custom initialization} return self ;} -(void) viewDidLoad {[super viewDidLoad]; self. imagedata = nil; // create the Title Tag self. header = [[UILabel alloc] init]; self. header. text = @ ""; self. header. textAlignment = NSTextAlignmentCenter; [self. view addSubview: self. head Er]; [self. header setTranslatesAutoresizingMaskIntoConstraints: NO]; // create an image view 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 setTranslatesAutor EsizingMaskIntoConstraints: NO]; // The previous button UIButton * prevButton = [[UIButton alloc] init]; prevButton. frame = CGRectMake (0, 20,300, 20); [prevButton setBackgroundColor: [UIColor redColor]; [prevButton setTitle: @ "previous" forState: UIControlStateNormal]; [prevButton addTarget: self action: @ selector (onShowPrevImage :) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: prevButton]; [prev Button setTranslatesAutoresizingMaskIntoConstraints: NO]; // The Button UIButton * nextButton = [[UIButton alloc] init] After creation; nextButton. frame = CGRectMake (0, 20,300, 20); [nextButton setBackgroundColor: [UIColor redColor]; [nextButton setTitle: @ "Next" forState: UIControlStateNormal]; [nextButton addTarget: self action: @ selector (onShowNextImage :) forControlEvents: UIControlEventTouchUpInside]; [self. view addSu Bview: nextButton]; [nextButton failed: NO]; // constraints NSMutableArray * contraits = [NSMutableArray array]; NSDictionary * metrics = [NSDictionary failed: @ 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: [NSLayoutCo Nstraint constraintsWithVisualFormat: @ "H: |-Padding-[imageView]-Padding-|" options: 0 metrics: metrics views: views]; [contraits outputs: [NSLayoutConstraint constraintsWithVisualFormat: @ "V: |-VDist-[header]-Padding-[imageView]-(> = VDist)-|" options: 0 metrics: metrics views: views]; // vertical center [self. view addConstraint: [NSLayoutConstraint constraintWithItem: prevButton attribute: NSLayoutAttributeCe NterY 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) didReceiveMemor YWarning {[super secure];}-(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, NSURLRes Ponse * response, NSError * error) {self. imageView. image = nil; self. imagedata = [UIImage imageWithData: data]; [self generated mselecw.mainthread: @ 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 requ EstWithURL: URL]; NSURLSession * session = [NSURLSession sharedSession]; prepare * task = [session dataTaskWithRequest: request completionHandler: ^ (NSData * data, NSURLResponse * response, NSError * error) {self. imageView. image = nil; self. imagedata = [UIImage imageWithData: data]; [self generated mselecw.mainthread: @ selector (updateMyImage) withObject: nil waitUntilDone: NO];}]; [task resume] ;}-(Void) updateMyImage {if (! Self. imageView. image) self. imageView. image = self. imagedata; return ;}@ end
4. Run

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.