2012-10-28 55 views
0

在我的項目中,我將圖像保存到手機上的文檔文件夾中,然後在單獨的tableview中加載它們。我獲得了一些成功,最後拍攝的圖像被加載到表格中,但被加載到每一行而不是最後一個。下面是我用在tableview中加載圖像的代碼:將保存在plist中的所有圖像加載到tableview中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"List"; 
ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
//Load PLIST 
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [path objectAtIndex:0]; 
NSString *plistPath = [NSString stringWithFormat:@"%@/images.plist", documentsDirectory]; 
//Load PLIST into mutable array 
NSMutableArray *imageArray = [NSMutableArray arrayWithContentsOfFile:plistPath]; 

for (NSDictionary *dict in imageArray) { 
//Do whatever you want here, to load an image for example 
    NSString *imageFilePath = [NSHomeDirectory() stringByAppendingPathComponent:[dict objectForKey:@"Original Image"]]; 
    UIImage *image = [UIImage imageWithContentsOfFile:imageFilePath]; 
    [cell.imageofItem setImage:image]; 
} 
} 

這裏是正在發生的事情 的例子:說我拿2張照片,一個被稱爲「10282012_13113138_image.jpg」,另一個叫「10282012_13113468_image.jpg」。然後我去加載單元格中的圖像,最後一張圖片加載到兩個單元格中。

任何幫助將不勝感激!

+2

我不知道這是如何工作的,因爲'UIImage 'image在for循環中聲明,但是在for循環的上下文之外使用。 – bobnoble

+0

@bobnoble對不起,我輸入了錯誤。現在修復它 –

+0

其中是細胞初始化或分配在您的 - (void)loadImages? – yeesterbunny

回答

1

而不是

for (NSDictionary *dict in imageArray) { 
    NSString *imageFilePath = [NSHomeDirectory() stringByAppendingPathComponent:[dict objectForKey:@"Original Image"]]; 
    UIImage *image = [UIImage imageWithContentsOfFile:imageFilePath]; 
    [cell.imageofItem setImage:image]; 

}

嘗試

NSDictionary *dict = [imageArray objectAtIndex:indexPath.row]; 
    NSString *imageFilePath = [NSHomeDirectory() stringByAppendingPathComponent:[dict objectForKey:@"Original Image"]]; 
    UIImage *image = [UIImage imageWithContentsOfFile:imageFilePath]; 
    [cell.imageofItem setImage:image]; 

的問題是,對於每個indexPath.row,你是迭代,直到數組中的最後一個元素,不斷改寫細胞圖像,直到你到達最後的圖像。然後爲下一個indexPath.row,你做同樣的事情,並將其設置爲陣列中的最後一個圖像,依此類推......

+0

正是我在找什麼,非常感謝! –