【问题标题】:How to download multiple images of table view cell in background?如何在后台下载表格视图单元格的多个图像?
【发布时间】:2012-05-02 05:50:30
【问题描述】:

我想在 tableView 的一行中创建一个应用程序,会有 4 个按钮图像,这些图像将从后台的服务器加载,因为如果我直接加载它们,那么表格视图会挂起一些。为此,我使用此代码在单元格中创建按钮并执行以在后台下载图像。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *hlCellID = @"hlCellID";

        UITableViewCell *hlcell = [tableView dequeueReusableCellWithIdentifier:hlCellID];
        if(hlcell == nil) {
            hlcell =  [[[UITableViewCell alloc] 
                        initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hlCellID] autorelease];
            hlcell.accessoryType = UITableViewCellAccessoryNone;
            hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        int section = indexPath.section;
        NSMutableArray *sectionItems = [sections objectAtIndex:section];

        int n = [sectionItems count];

        int i = 0, j = 0, tag = 1;
        int x = 10;
        int y = 30;

        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        for (i = 1; i<= n ; i++) //[arr count]
        {
            for(j=1; j<=4;j++)
            {

                if (i>=n) break;
                Item *item = [sectionItems objectAtIndex:i];

                CGRect rect = CGRectMake(x = x, y = y, 68, 65); 
                UIButton *button=[[UIButton alloc] initWithFrame:rect];
                [button setFrame:rect];
                UIImage *buttonImageNormal=[UIImage imageNamed:item.image];
                [button setBackgroundImage:buttonImageNormal    forState:UIControlStateNormal];
                [button setContentMode:UIViewContentModeCenter];
                // set the image to be loaded (using the same one here but could/would be different)
                NSURL *imgURL = [NSURL URLWithString:@"http://londonwebdev.com/wp-content/uploads/2010/07/featured_home.png"];      

                // Create an array with the URL and imageView tag to 
                // reference the correct imageView in background thread.
                NSMutableArray *arr = [[NSArray alloc] initWithObjects:imgURL, [NSString stringWithFormat:@"%d", tag], nil  ];

                // Start a background thread by calling method to load the image
                [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
    //          button.tag = [tagValue intValue];
                button.tag = tag;
                //NSLog(@"....tag....%d", button.tag);

                [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
                [hlcell.contentView addSubview:button];
                [button release];

                tag++;

                x = x + 77; 

            }
            x = 10;
            y = y + 74;
        }
        [pool release];
        return hlcell;
    }

上面的代码完美运行,但是当我下载图像并尝试分配某个特定按钮时,我找不到按钮标签,尽管我可以在 touchupinside 操作时找到按钮标签。

- (void) loadImageInBackground:(NSArray *)urlAndTagReference  {

    NSLog(@"Received URL for tagID: %@", urlAndTagReference);

    // Create a pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Retrieve the remote image. Retrieve the imgURL from the passed in array
    NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
    UIImage *img    = [[UIImage alloc] initWithData:imgData];

    // Create an array with the URL and imageView tag to 
    // reference the correct imageView in background thread.
    NSMutableArray *arr = [[NSArray alloc] initWithObjects:img, [urlAndTagReference objectAtIndex:1], nil  ];

    // Image retrieved, call main thread method to update image, passing it the downloaded UIImage
    [self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];

    [pool release];

}

    - (void) assignImageToImageView:(NSArray *)imgAndTagReference
    {

        // Create a pool
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        int i;
        UIButton *checkView;

    //  [imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
    //    UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
    //    UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
    //    profilePic.image = [imgAndTagReference objectAtIndex:0];


    //  checkView.tag = [[imgAndTagReference objectAtIndex:1] intValue];
        // loop
        for (UIButton *checkView in [self.tblImage subviews] ) 
        { i++;
            NSLog(@"Checking tag: %d against passed in tag %d",checkView.tag, [[imgAndTagReference objectAtIndex:1] intValue]);
            if ([checkView tag] == [[imgAndTagReference objectAtIndex:1] intValue]) {

                if (i==35) break;
                // Found imageView from tag, update with img
    //          [checkView setImage:[imgAndTagReference objectAtIndex:0]];
                [checkView setImage:[imgAndTagReference objectAtIndex:0] forState:UIControlStateNormal];

                //set contentMode to scale aspect to fit
                checkView.contentMode = UIViewContentModeScaleAspectFit;

                //change width of frame
                CGRect frame = checkView.frame;
                frame.size.width = 80;
                checkView.frame = frame;

            }
        }   

        // release the pool
        [pool release];

        // Remove the activity indicator created in ViewDidLoad()
        [self.activityIndicator removeFromSuperview];

    }

所有代码都能完美运行,但我在这里for (UIButton *checkView in [self.tblImage subviews] 找不到表格单元格子视图,那么如何找到表格单元格子视图的子视图。?

【问题讨论】:

  • 先生,我看过这个例子,但我认为这不能满足我的问题。
  • 请直呼我的名字。如果您在 UITableview 中有 n 个图像,那么您必须采用延迟加载概念。这意味着首先加载所有轻量级组件,例如 UILabels、UIButton。经过一些延迟后,开始在后台线程中加载图像(最好在 0.3 秒后)。通过这种方式,您可以获得良好的可靠性能。
  • 你能告诉我如何找到表格单元格的子视图吗?在这里你可以看到UIButton *checkView in [self.tblImage subviews] 我已经使用了这个代码,但它没有给我表格视图行单元格项目中子视图的计数。
  • @NaveenThunga 谢谢我通过传递行索引解决了我的问题,现在我正在为多行索引路径实现。

标签: iphone uitableview


【解决方案1】:

你可以使用SDWebImage

网页图片 该库为 UIImageVIew 提供了一个类别,支持来自网络的远程图像。

它提供:

向 Cocoa Touch 框架添加 Web 图像和缓存管理的 UIImageView 类别 一个异步图片下载器 具有自动缓存过期处理的异步内存 + 磁盘映像缓存 保证不会多次下载相同的 URL 保证不会一次又一次地重试虚假 URL 表演!

随便用吧

[youImageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageRetryFailed];

【讨论】:

  • 请查看更新问题并指导我该怎么做?这所有代码在滚动视图中都能完美运行,但我想在表格视图中创建。因为我也想做搜索功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多