2011-03-07 19 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

相關問題