如何在iphone应用程序的Table Cell中加载背景图像

时间:2010-07-09 13:33:32

标签: iphone objective-c iphone-sdk-3.0 uitableview

我开发了一个RSS应用程序。在我的表格单元格中,我显示的图像是我从RSS提要和标题中的imge链接中检索的。 图像已成功加载,但问题是它挂起了我的应用程序。 因为有任何方法可以在后台加载图像。 我目前的代码是。

int blogEntryIndex1 = [indexPath indexAtPosition: [indexPath length] -1];
        imgstring=[[blogEntries objectAtIndex: blogEntryIndex1] objectForKey: @"image"];
NSURL *url = [NSURL URLWithString:imgstring];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:data];
     cell.imageView.image=[img autorelease];

任何想法,请提前致谢...

4 个答案:

答案 0 :(得分:4)

重新发布...您还应该通过Apple的示例代码http://developer.apple.com/iphone/library/samplecode/LazyTableImages/Introduction/Intro.html来查看延迟表加载

更新此处的另一个示例:http://www.markj.net/iphone-asynchronous-table-image/

答案 1 :(得分:1)

好吧我们已经完成了代码是......

- (void) loadImage:(id)object {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// Get the data to pass in
NSDictionary *dict = (NSDictionary *)object;

// Get the cell and the image string
NSString *imgstring = [dict objectForKey:@"imgstring"];
MyfirstCell *cell = [dict objectForKey:@"cell"];

NSURL *url = [NSURL URLWithString:imgstring];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
    cell.myimnage.image = img;
[pool release];

}

我将在我的代码中调用上述方法......

if(searching) {
        //cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
        int blogEntryIndex = [indexPath indexAtPosition: [indexPath length] -1];
        // Tell your code to load the image for a cell in the background
        NSString *imgstring =[[blogEntries objectAtIndex: blogEntryIndex] objectForKey: @"image"];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:cell, @"cell", imgstring, @"imgstring", nil];
        [self performSelectorInBackground:@selector(loadImage:) withObject:dict];
        //background code end here..

感谢deanWombourne给了我这个代码......

答案 2 :(得分:0)

另请参阅Apple的这份文件。

http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html

大部分时间我使用NSURLConnection下载内容。

答案 3 :(得分:-2)

您可以这样使用:

((UIImageView *)cell.backgroundView).image = bgImage;
((UIImageView *)cell.selectedBackgroundView).image = bgImage;