0

我正在创建一个静态表格视图(必须与 iOS 4 兼容 - 所以我不能使用 iOS 5 的方法)。

我的方式是我有两个部分;第一个有一个单元格,第二个有两个单元格。我制作了两个数组,一个带有第一部分中唯一单元格的标题,第二个带有第二部分中两个单元格的标题。所以我的字典是这样的:

(NSDictionary *)  {
    First =     (
        Title1       < --- Array (1 item)
    );
    Second =     (
        "Title1",    < --- Array (2 items)
        Title2   
    );
}

我遇到的问题是我需要使用tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section. 所以我的问题是,如何使用 检索字典中的部分NSInteger section?我也必须在tableView:cellForRowAtIndexPath.

谢谢

4

3 回答 3

1

如果您不了解字典的工作原理,我建议您简化问题。为每个部分创建一个数组,然后在您的委托方法中使用 switch() 语句调用 [array count] 以获取行数等。对于部分计数,您仍然可以使用带有 [[dictionary allKeys] count] 的原始字典。

编辑:我刚刚看到@fzwo 在两条评论中推荐了同样的东西

于 2012-06-15T07:44:21.777 回答
1

如前所述,您最好的选择是数组数组。为避免字典的复杂性,NSArray请为表数据和节标题创建两个 ivars。

// in viewDidLoad

tableData = [NSArray arrayWithObjects:
   [NSArray arrayWithObjects:
      @"Row one title", 
      @"Row two title", 
      nil],
   [NSArray arrayWithObjects:
      @"Row one title", 
      @"Row two title", 
      @"Row three title", 
      nil],
   nil]; 
sectionTitles = [NSArray arrayWithObjects:
   @"Section one title",
   @"Section two title", 
   nil]; 

// in numberOfSections: 
return tableData.count;

// in numberOfRowsInSection:
return [[tableData objectAtIndex:section] count];

// in titleForHeaderInSection:
return [sectionTitles objectAtIndex:section];

// in cellForRowAtIndexPath:
...
cell.textLabel.text = [[tableData objectAtIndex:indexPath.section]
                       objectAtIndex:indexPath.row];

如果您需要更多可用于单元格的数据,您可以使用其他对象而不是行标题。

于 2012-06-15T08:23:53.483 回答
-3

要获取部分中的行数,您可以使用以下命令:

tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *key = [[dictionary allKeys] objectAtIndex: section];
    return [[dictionary objectForKey:key] count];
}

并获取单元格值:

tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [[dictionary allKeys] objectAtIndex: indexPath.section];
    NSArray *values = [dictionary objectForKey:key];
    NSString *value = [values objectAtIndex: indexPath.row];

    // code to create a cell

    return cell;
}
于 2012-06-14T21:52:39.930 回答