2012-06-14 42 views
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中做同样的事情。

谢谢

+0

静态是如何“静态”的?如果表大小真的是不可变的,那么你不能只是在tableView中做一个切换部分:(UITableView *)tableView numberOfRowsInSection:(NSInteger)部分并返回适当的值? – strings42

+1

你为什么要用字典?如果你不太严重地简化你的问题,这只会让问题复杂化。如果它只有两个数组,只需使用两个iVar;如果它是任意数量的需要保持有序的数组,则使用一组数组。 – fzwo

回答

1

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

编辑: 我刚才看到@fzwo建议两点意见

-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; 
} 
+1

-1。在'allKeys'的文档中明确指出:**数组中元素的顺序没有定义。** – fzwo

+0

@fzwo然后缓存它们或使用OrderedDictionary:http://cocoawithlove.com/2008/12 /ordereddictionary-subclassing-cocoa.html –

+0

这对于手头的问题来说是完全矫枉过正的。即使是字典本身也是过分矫枉过正的事情,正如问题的存在所证明的那样。 – fzwo

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]; 

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