IOS TableView远程图片加载笔记

搞了一天TableView,晚饭时终于搞定,现在来整理整理。希望可以帮助到可以帮助的人。(最后附demo下载地址)

先上图:


//
//  SwwTableViewController.m
//  tableviewdemo
//
//  Created by hundsun on 14-9-14.
//  Copyright (c) 2014年 Robinson_911. All rights reserved.
//  本人博客地址: http://blog.csdn.net/robinson_911


#import "SwwTableViewController.h"
#import "SwwTableViewCell.h"
#import "DownloadHelper.h"

@interface SwwTableViewController ()
-(void)startIconDownload:(SwwTableViewCell*) shopdata forIndexPath:(NSIndexPath*) indexPath;
@end

@implementation SwwTableViewController

@synthesize myArray;
@synthesize items;
@synthesize imageDownloadProgress;
NSString *books;
NSString *prices;
-(void) loadJsonData:(NSURL *)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    DownloadHelper *help = [[DownloadHelper alloc] initWithRequest:request];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(parseJsonData:) name:@"connectionFinished" object:help];
    [[help connection] start];
}

-(void) parseJsonData:(NSNotification *)n
{
    items = [[NSMutableArray alloc]initWithCapacity:0];
    DownloadHelper* help = [n object];
    NSData *data = [help receivedData];
    NSError *error;
    NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (json == nil) {
        NSLog(@"json parse failed \r\n");
        return;
    }
    
    for (int i=0; i < [json count]; i++) {
        NSArray *s = [json objectAtIndex:i];
        SwwTableViewCell *shopdata = [[SwwTableViewCell alloc] init];
        shopdata.text1= [s objectAtIndex:1];
        shopdata.text2 = [s objectAtIndex:3];
        shopdata.text3 = [s objectAtIndex:0];
        shopdata.url = [s objectAtIndex:2];
        [self.myArray addObject:shopdata];
        [shopdata release];
    }
    [self.tableView reloadData];
}


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    
    self.myArray = [NSMutableArray array];
    NSURL *url = [NSURL URLWithString:kDoubanUrl];
    [self loadJsonData:url];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 2;

}*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
     return [myArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TableViewDynamicLoadIdentifier = @"TableViewDynamicLoadIdentifier";
	
	SwwTableViewCell *cells = [tableView dequeueReusableCellWithIdentifier:TableViewDynamicLoadIdentifier];
	if (cells == nil)
	{
        cells = [[[SwwTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                       reuseIdentifier:TableViewDynamicLoadIdentifier]autorelease] ;
		cells.selectionStyle = UITableViewCellSelectionStyleNone;
	}

//   cells.parent=self;
 //  cells.label1.text = @"55元" ;
 //  cells.label2.text = @"邓小平" ;
   // [cells setCell];
   // return cells;
    
 //   NSLog(@"%@",dic);
 //   NSLog(@"%@",cells.dic);
	
	NSInteger nRow = [indexPath row];
	SwwTableViewCell *shopdata = [self.myArray objectAtIndex:nRow];
	
	cells.label1.text = shopdata.text1;
    cells.label2.text = shopdata.text2;
    
    if (shopdata.appIcon) {
        cells.imageView.image = shopdata.appIcon;
    }else{
        if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
		{
			[self startIconDownload:shopdata forIndexPath:indexPath];
		}
        
        cells.imageView.image = [UIImage imageNamed:@"Placeholder"];
    }

    return cells;
}


-(void)startIconDownload:(SwwTableViewCell *)shopdata forIndexPath:(NSIndexPath *)indexPath{
    IconDownloader *iconDownloader = [imageDownloadProgress objectForKey:indexPath];
    NSLog(@"startIconDownload iconDownloader=%@",iconDownloader);
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = shopdata;
        iconDownloader.indexPathInTableView = indexPath;
        iconDownloader.delegate = self;
        [imageDownloadProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
        [iconDownloader release];
    }
}


-(void)appImageDidLoad:(NSIndexPath *)indexPath{
    IconDownloader *iconDownloader = [imageDownloadProgress objectForKey:indexPath];
    if (iconDownloader != nil)
    {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:iconDownloader.indexPathInTableView];
        
        // Display the newly loaded image
        cell.imageView.image = iconDownloader.appRecord.appIcon;
    }
    
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([self.myArray count] > 0)
    {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            SwwTableViewCell *shopdata = [self.myArray objectAtIndex:[indexPath row]];
            
            if (!shopdata.appIcon)
            {
                NSLog(@"start download nrow=%d",[indexPath row]);
                [self startIconDownload:shopdata forIndexPath:indexPath];
            }
        }
    }
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *titileString = [NSString stringWithFormat:@"你点击了按钮%d",[indexPath row]];
    UIAlertView *alert = [[ UIAlertView alloc]initWithTitle:@"提示" message:titileString delegate:self    cancelButtonTitle:@"OK"otherButtonTitles: nil];
    [alert show];
    int rownum = [indexPath row];
    NSLog(@"===row=%d",rownum);
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}
@end

demo下载地址:http://download.csdn.net/detail/robinson_911/7916253

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值