iPhone tableview:titleForHeaderInSection 派生自数组

Posted

技术标签:

【中文标题】iPhone tableview:titleForHeaderInSection 派生自数组【英文标题】:iPhone tableview: titleForHeaderInSection derived from array 【发布时间】:2010-05-03 23:07:45 【问题描述】:

我有一个由数组填充的表格视图。目前 tableview 没有分组。我想做的是检查每个数组对象的值,例如状态,并将所有 CA 项目组合在一起,将所有 OR 项目组合在一起等。然后,为这些组分配一个标题。

数组是动态的,将来会增长并获得新值,所以我不能硬编码标题,我希望这些以某种方式来自我的初始数组。

目前我正在使用以下内容,但它没有考虑数组的排序,或者我删除了数组中与加利福尼亚有关的所有项目。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section  
 if (section == 0) 
  return @"California";
  else if (section == 1) 
  return @"Washington";
  else 
  return @"Utah";
 
//end tableView

所以,我对这怎么可能感到困惑。任何提示将不胜感激。

【问题讨论】:

【参考方案1】:

每个州/省/等都有一个数组,并使用该州作为键将这些数组放入字典中。然后是另一个包含所有状态键的数组。添加或删除字典时,使用 keysSortedByValueUsingSelector 创建/更新状态键数组。还有一些像这样的代码来实现表委托......

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    return [stateKeyArray count];


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
    return [stateKeyArray objectAtIndex:section];


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    NSString* stateKey = [stateKeyArray objectAtIndex:section];
    return [[dataDict objectForKey:stateKey] count];

编辑:这些数组和字典可以这样声明:

// key=state (an NSString), obj=NSMutableArray of AddressRecord objects
NSMutableDictionary* dataDict; 

// sorted array of state keys (NSString)
NSMutableArray* stateKeyArray;   

要添加新的地址记录,应该这样做。你需要类似的东西来删除一个地址,但你现在应该有足够的东西来解决这个问题了。

-(void)addAddress:(AddressRecord* addr) 
    NSMutableArray* stateArray = [dataDict objectForKey:addr.state];

    if (stateArray==nil) 
       // adding a new state
       stateArray = [NSMutableArray new];
       [dataDict setObject:stateArray forKey:addr.state];  // add state array to dict
       [stateArray release];

       // update array of state keys (assuming they are NSString)
       self.stateKeyArray = [dataDict keysSortedByValueUsingSelector:@selector(localizedCompare:)];
    

    [stateArray addObject:addr];   // add address to state array

【讨论】:

好的,现在我们到了这里。有没有一种基于 if 语句创建单独数组的好方法?所以,我可以检查我的初始数组中的每个项目是否来自某个状态,然后将它们推送到另一个数组中。只是不确定这将如何工作......

以上是关于iPhone tableview:titleForHeaderInSection 派生自数组的主要内容,如果未能解决你的问题,请参考以下文章

iphone使用自定义单元格滚动tableview太慢了

如何将数据添加到 iPhone 上的 TableView?

iPhone 4.3 的 Tableview 中的多个单元格选择

如何创建类似于 iphone 铃声设置的 tableview?

iphone中的tableView没有更新

iPhone Tableview 在水平滚动而不是垂直中使用单元格