使用唯一的图像和文本配置UITableViewCell对象

时间:2011-02-03 16:55:59

标签: iphone objective-c uitableview

给定.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按照UITableView单元格中的字母顺序递增。不起作用的是cell.imageView.image

它将afghanistan.png置于第一个UITableViewCell中。接下来的细胞也会收到afghanistan.png。 (第二个单元格应该接收'albania.png'等)。我该如何解决这个UIImageView问题?

2 个答案:

答案 0 :(得分:2)

改为使用imageNamed

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

答案 1 :(得分:1)

你应该使用 [item objectForKey:@"image"]代替 [item objectForKey:@"imageKey"] (因为.plist使用<key>image</key>)。