2013-03-08 2 views
0

я использую представление таблицы для отображения изображения Фрона Интернета и его времени принимая, чтобы загрузить изображение ..нагрузки Tableview

я попытался

dispatch_async(imageQueue_, ^{ 
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[record imageURLString]]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [[cell imageView] setImage:[UIImage imageWithData:imageData]]; 
     [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; 
    }); 

, но его изображения загрузки медленно и повторяя изображения Till другие изображения будут загружаться в том же ряду. есть ли способ загрузить все изображения в виде таблицы в одно и то же время (как правило, это произойдет один за другим ..)?

+0

использование ленивая погрузка для показа изображения – Dhara

+0

использование sdwebimage. – Eugene

+0

@Dhara: Я не получаю, как использовать ленивую загрузку. – Raju

ответ

0

As Eugene упомянутый, использование SDWebImage. Делает это так просто.

1

сделать 2 класса с AsyncImageView.h и .m

В AsyncImageView.h

@interface AsyncImageView : UIView 
{ 
    NSURLConnection *connection; 
    NSMutableData *data; 
    NSString *urlString; // key for image cache dictionary 
} 

-(void)loadImageFromURL:(NSURL*)url; 
- (void)StoreImage:(UIImage*)image String:(NSString *)str; 
@end 

и В .м

- (id)initWithFrame:(CGRect)frame { 
    if (self = [super initWithFrame:frame]) 
    { 
    } 
    return self; 
} 


- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 
} 


- (void)dealloc 
{ 
    [connection cancel]; 
    [connection release]; 
    [data release]; 
    [super dealloc]; 
} 

-(void)loadImageFromURL:(NSURL*)url 
{ 
    if (connection != nil) 
    { 
     [connection cancel]; 
     [connection release]; 
     connection = nil; 
    } 
    if (data != nil) 
    { 
     [data release]; 
     data = nil; 
    } 

    if (imageCache == nil) // lazily create image cache 
     imageCache = [[ImageCache alloc] initWithMaxSize:2*1024*1024]; // 2 MB Image cache 

    [urlString release]; 
    urlString = [[url absoluteString] copy]; 
    UIImage *cachedImage = [imageCache imageForKey:urlString]; 
    if (cachedImage != nil) { 
     if ([[self subviews] count] > 0) 
     { 
      [[[self subviews] objectAtIndex:0] removeFromSuperview]; 
     } 
     UIImageView *imageView = [[[UIImageView alloc] initWithImage:cachedImage] autorelease]; 
     imageView.contentMode = UIViewContentModeScaleAspectFill; 
     imageView.autoresizingMask = 
      UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
     [self addSubview:imageView]; 
     imageView.frame = self.bounds; 
     [imageView setNeedsLayout]; // is this necessary if superview gets setNeedsLayout? 
     [self setNeedsLayout]; 
     return; 
    } 

#define SPINNY_TAG 5555 

    UIActivityIndicatorView *spinny = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    spinny.backgroundColor=[UIColor whiteColor]; 
    // spinny.tag = SPINNY_TAG; 
    // spinny.center = self.center; 
    [spinny startAnimating]; 
    [self addSubview:spinny]; 
    [spinny release]; 

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)incrementalData 
{ 
    if (data==nil) 
    { 
     data = [[NSMutableData alloc] initWithCapacity:2048]; 
    } 
    [data appendData:incrementalData]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection 
{ 
    [connection release]; 
    connection = nil; 

    UIView *spinny = [self viewWithTag:SPINNY_TAG]; 
    [spinny removeFromSuperview]; 
    if ([[self subviews] count] > 0) 
    { 
     [[[self subviews] objectAtIndex:0] removeFromSuperview]; 
    } 
    UIImage *image = [UIImage imageWithData:data]; 
    [imageCache insertImage:image withSize:[data length] forKey:urlString]; 
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease]; 
    imageView.contentMode = UIViewContentModeScaleAspectFill; 
    imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    [self addSubview:imageView]; 
    imageView.frame = self.bounds; 
    [imageView setNeedsLayout]; 
    [self setNeedsLayout]; 
    [data release]; 
    data = nil; 
} 

А в классе, где вы показываете TableView просто импортировать AsyncImageView.h и в tableView cellForRowAtIndexPath написать

AsyncImageView *asyncImageView = nil; 

    UIImageView *cellImage = (UIImageView *)[cell viewWithTag:1]; 
    asyncImageView = [[AsyncImageView alloc] initWithFrame:cellImage.frame] ; 
    [asyncImageView loadImageFromURL:YourImageURL]; 
    asyncImageView.backgroundColor=[UIColor clearColor]; 
    [cell.contentView addSubview:asyncImageView]; 

Я использовал его и отлично работает. Надеюсь, это сработает и для вас. :)

+0

Что такое imageCache? – Raju

0

Вы загружаете изображения лениво в таблицу. Here - отличный пример от Apple.

+0

Я не получаю, как использовать ленивую загрузку изображения в моей программе .. – Raju

Смежные вопросы