将URL中的图像加载到UITableViewCell的UIImageView中

Aho*_*tbi 4 objective-c ios4 ios

我有以下代码:(注意:newsImageURLNSArray)

NSString *imagesURL = @"http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage02.png,http://aud.edu/images/newsimage03.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,";
newsImageURL = [[NSArray alloc] initWithArray:[AllNewsHeadLine componentsSeparatedByString:@","]];
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下代码将这些图像加载到单元格中:

NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [newsImageURL objectAtIndex:indexPath.row]]]; 
cell.image = [UIImage imageWithData:imageData];
Run Code Online (Sandbox Code Playgroud)

相反,当我使用此行时,图像加载正常:

cell.image = [UIImage imageNamed:@"imagename.png"];
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

apo*_*rat 9

您应该使用支持缓存,默认占位符和延迟加载图像的现有框架.

https://github.com/rs/SDWebImage是一个很好的简单框架

#import "UIImageView+WebCache.h"

...

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:MyIdentifier] autorelease];
    }

    // Here we use the new provided setImageWithURL: method to load the web image
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

  • 他问为什么上面的代码不起作用......我也想知道它...添加一个框架不是正确答案而且没有帮助 (3认同)