éåæéä¿¡ã§ç»åããã¼ãããæ¹æ³ã«ã¤ãã¦
UITableViewãªã©ã®ã¹ã¯ãã¼ã«ç³»ã®Viewã§ãµã ãã¤ã«ç»åãåºãå ´åãä¸è¨ã®ãããªè¨è¿°ã§ã¯ã¡ã¤ã³ã¹ã¬ããã§ç»åããã¼ãããããããã¦ã¼ã¶ã¼ã®UIæä½ã«å½±é¿ãåºã¦ãã¾ãã¾ãã
NSURL *url = [NSURL URLWithString:@"URL"]; NSData *data = [NSData dataWithContentsOfURL:url]; [instanceOfUIImageView setImage:[[UIImage alloc] initWithData:data]];
ããããå ´åã¯éåæéä¿¡ãè¡ãã®ãå®ç³ã ã¨æãã¾ãããåèã«ãªããµã³ãã«ããã¾ãç¡ãã£ãã®ã§è©¦ãã«ä½ã£ã¦ã¿ã¾ãããUIImageViewãç¶æ¿ããUIAsyncImageViewã¯ã©ã¹ã§ãã
UIAsyncImageView.h
ç»åURLã®æå®ã¨ãéä¿¡ä¸æ¢ç¨ã®ã¡ã½ããã®ã¿å®ç¾©ãã¦ãã¾ãã
#import <Foundation/Foundation.h> @interface UIAsyncImageView : UIImageView { @private NSURLConnection *conn; NSMutableData *data; } -(void)loadImage:(NSString *)url; -(void)abort; @end
UIAsyncImageView.m
NSURLConnectionã«ããéåæéä¿¡ã§ç»åãã¼ã¿ãåå¾ãã¦ãã¾ãã
connectionXXXç³»ã®ã¡ã½ããã¯ä¸è¨ã¯ã©ã¹ã®ããªã²ã¼ãã¡ã½ããã§ãã
#import "UIAsyncImageView.h" @implementation UIAsyncImageView -(void)loadImage:(NSString *)url{ [self abort]; self.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.2]; data = [[NSMutableData alloc] initWithCapacity:0]; NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ [data setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)nsdata{ [data appendData:nsdata]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ [self abort]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ self.image = [UIImage imageWithData:data]; self.contentMode = UIViewContentModeScaleAspectFit; self.autoresizingMask = UIViewAutoresizingFlexibleWidth || UIViewAutoresizingFlexibleHeight; [self abort]; } -(void)abort{ if(conn != nil){ [conn cancel]; [conn release]; conn = nil; } if(data != nil){ [data release]; data = nil; } } - (void)dealloc { [conn cancel]; [conn release]; [data release]; [super dealloc]; } @end
å©ç¨æ¹æ³
UIImageViewã¨åæ§ã§ãã
loadImageãå¼ã³åºãã¨éä¿¡ãéå§ããããã¼ã¿åå¾å®äºãã段éã§ç»é¢ã«è¡¨ç¤ºããã¾ãã
UIAsyncImageView *ai = [[UIAsyncImageView alloc] initWithFrame:CGRectMake(0,0,50,50)]; [ai loadImage:@"URL"]; [self.view addSubview:ai];
Flickrãµã³ãã«
Flickrã®APIã使ã£ã¦UIScrollViewã«è¡¨ç¤ºãããµã³ãã«ã§ããUITableViewã§ã¯ãªãã§ãããå®æ©ã§ãã¹ã ã¼ãºã«åä½ãã¦ãã¾ããè§ä¸¸ã«ããã©ã¤ãã©ãªãçºè¦ããã®ã§å ¥ãã¦ã¿ã¾ããã
åè
ãã®ä»
UITableViewã¸ç»åã表示ããå ´åã¯ãå°ã工夫ãããã®ã§ããã ãã§ã¯ä¸æãããã¾ãããiOS Dev Centerã«ãããLazyTableImagesã¨ãããµã³ãã«ãåèã«ãªãã¾ãã