2011-02-03 20 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>)。