2011-03-07 18 views
0

我在iOS项目中有几个hunderd .jpgs/Resources中。从NSArray中将图像加载到UITableViewCell中

这里是viewDidLoad方法:

- (void)viewDidLoad { 


    NSArray *allPosters = [[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:@"."]; 

    [super viewDidLoad]; 

} 

上面成功地加载所有.jpgs的成NSArray。 我只需要这个数组内UITableViewCellsUITableView

这里显示的所有.jpgs的是-(UITableViewCell *)tableView:cellForRowAtIndexPath:方法:

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

    static NSString *CellIdentifier = @"Cell"; 

    NSDictionary *posterDict = [allPosters objectAtIndex:indexPath.row]; 
    NSString *pathToPoster= [posterDict objectForKey:@"image"]; 

    UITableViewCell *cell = 
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell ==nil) { 

     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease]; 


      } 

    UIImage *theImage = [UIImage imageNamed:pathToPoster]; 
    cell.ImageView.image = [allPosters objectAtIndex:indexPath.row]; 
    return cell; 
} 

我知道这个问题是与cell.ImageView.image,但我不知道是什么问题是什么?我如何从阵列中抓取每个.jpg并在每一行中显示?

回答

2
NSArray *allPosters = [[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:@"."]; 

这会给你一个路径数组(如方法名所示)。那些路径是NSStrings。 但是你将这个数组赋值给一个局部变量,并且在你离开viewDidLoad之后这个变量将会消失。

,所以你必须把它变成是这样的:

allPosters = [[[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:@"."] retain]; 

还有一句:

NSDictionary *posterDict = [allPosters objectAtIndex:indexPath.row]; 
NSString *pathToPoster= [posterDict objectForKey:@"image"]; 

这肯定会崩溃,如果你会正确分配数组。

它变成

NSString *pathToPoster = [allPosters objectAtIndex:indexPath.row]; 

下一个:

UIImage *theImage = [UIImage imageNamed:pathToPoster]; 
cell.ImageView.image = [allPosters objectAtIndex:indexPath.row]; 

UIImages imageNamed:不与路径工作,它需要的文件名。当然,您想要将真实图像分配给imageview,而不是指向海报的路径。所以,改变它:

UIImage *theImage = [UIImage imageNamed:[pathToPoster lastPathComponent]]; 
cell.imageView.image = theImage; 
+0

谢谢,虽然我收到'请求会员'ImageView'的东西不是结构或联盟'? – mozzer 2011-03-07 14:38:06

+0

噢,没有发现。当然是cell.imageView.image。没有资本我 – 2011-03-07 14:39:36

1

这可能只是一个错字,但它应该是:

//lowercase "i" in imageView 
cell.imageView.image = [allPosters objectAtIndex:indexPath.row]; 

须─你所创建的UIImage * theImage,但你不使用它。那里发生了什么?

2

尝试使用[UIImage imageWithContentsOfFile:pathToPoster]而不是imageNamed。并将值设置为UIImage对象。

+0

+1谢谢,补充说,@ fluchtpunkt的答案和它的工作。 – mozzer 2011-03-07 15:24:14

相关问题