从pList数据源创建分组的UITableView

4

我在寻找一份易于理解的教程,介绍如何创建一个分组UITableView,并从pList文件中获取数据。

我遇到的问题是如何正确地构建pList文件以满足2个不同部分的需求。

1个回答

7

plist的根应该是一个数组。该数组应包含两个字典(即您的部分)。这些字典将包含两个键:一个用于部分标题,另一个用于部分中的行。

假设您已将plist读入NSArray * sections中,您可以使用以下代码返回部分、行数、部分标题和单元格标题。

您的plist文件应如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>Title</key>
        <string>Section1</string>
        <key>Rows</key>
        <array>
            <string>Section1 Item1</string>
            <string>Section1 Item2</string>
        </array>
    </dict>
    <dict>
        <key>Title</key>
        <string>Section2</string>
        <key>Rows</key>
        <array>
            <string>Section2 Item1</string>
            <string>Section2 Item2</string>
        </array>
    </dict>
</array>
</plist>




#import "RootViewController.h"

@interface RootViewController ()

@property (copy, nonatomic) NSArray* tableData;

@end


@implementation RootViewController

@synthesize tableData;

- (void) dealloc
{
    self.tableData = nil;
    [super dealloc];
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.tableData = [NSArray arrayWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"Table" ofType: @"plist"]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return [tableData count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return [[[tableData objectAtIndex: section] objectForKey: @"Rows"] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
    return [[tableData objectAtIndex: section] objectForKey: @"Title"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [[[tableData objectAtIndex: indexPath.section] objectForKey: @"Rows"] objectAtIndex: indexPath.row];

    return cell;
}

@end

我一直收到这个错误:“NSArray可能无法响应objectForKey”? - Andyy
我解决了那个错误。但是现在我的表格显示出来了,但是没有填充任何内容,没有章节或其他东西 =/ - Andyy
我已经追踪到我的问题部分在于...
  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int i = [[[tableData objectAtIndex: section] objectForKey: @"Rows"] count]; NSLog (@"%i", i); return [[[self.tableDataSource objectAtIndex: section] objectForKey: @"Rows"] count]; }我的NSLog告诉我它正在返回0。
- Andyy
我在我的回答中添加了可工作的代码 - 你确定在检查它的时候tableData不是nil吗?为了保险起见,在viewWillAppear中加入一个reloadData! - Steven Kramer
非常感谢您的帮助。问题出在我最初加载数据时。 - Andyy
现在我卡在了尝试让它深入子视图的过程中 =/ - Andyy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接