2011-02-03 44 views
2

一個UITableViewCell對象給出一個.plist類似於:配置具有獨特的圖像和文字

<plist version="1.0"> 
<array> 
    <dict> 
     <key>name</key> 
     <string>Afghanistan</string> 
     <key>government</key> 
     <string>Islamic Republic</string> 
     <key>population</key> 
     <integer>0</integer> 
     <key>image</key> 
     <string>/Flags/afghanistan.png</string> 
    </dict> 
    <dict> 
     <key>name</key> 
     <string>Albania</string> 
     <key>government</key> 
     <string>Emerging Democracy</string> 
     <key>population</key> 
     <integer>0</integer> 
     <key>image</key> 
     <string>/Flags/albania.png</string> 
    </dict> 
.... etc. 

而且ViewController.m

#import "FirstViewController.h" 
@implementation FirstViewController 
@synthesize sortedCountries; 

-(void)viewDidLoad { 

    NSString *path = [[NSBundle mainBundle] pathForResource:@"countries" ofType:@"plist"]; 

    NSArray *countries = [NSArray arrayWithContentsOfFile:path]; 
    NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]; 
    self.sortedCountries = [countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; 


} 

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

    NSDictionary *country = [sortedCountries objectAtIndex:indexPath.row]; 
     NSString *countryName = [country objectForKey:@"name"]; 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = 
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

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

    NSDictionary *item = (NSDictionary *)[sortedCountries objectAtIndex:indexPath.row]; 
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"image"] ofType:@"png"]; 
    UIImage *theImage = [UIImage imageWithContentsOfFile:path]; 

    cell.imageView.image = theImage; 
    cell.textLabel.text = countryName; 
    return cell; 

    } 

這使countryName在作爲expeted字母升序UITableView單元格。什麼不工作是cell.imageView.image

它將afghanistan.png放入第一個UITableViewCell,如預期的那樣。然而,下面的單元格也會收到afghanistan.png。 (第二個單元格應該收到'albania.png'等)。我該如何解決這個UIImageView問題?

回答

2

改爲使用imageNamed

cell.imageView.image = [UIImage imageNamed:[item objectForKey:@"image"]]; 
+0

你能詳細點嗎? – mozzer 2011-02-03 17:36:36

+0

如果你有`UIImage * theImage = [UIImage imageWithContentsOfFile:path];`將其更改爲`UIImage * theImage = [UIImage imageNamed:[item objectForKey:@「image」]];` – WrightsCS 2011-02-03 17:54:47

1

你應該在 [item objectForKey:@"imageKey"] 代替使用 [item objectForKey:@"image"](爲的.plist使用<key>image</key>)。