views:

148

answers:

1

I have an indexed table view that organizes cities in a state by their first letter. What I have working is an NSMutableDictionary is created with the keys of A,B,C,etc. and the corresponding cities are added to their respective arrays. ex:

Y =     (
    Yatesboro,
    Yeagertown,
    York,
    "York Haven",
    "York New Salem",
    "York Springs",
    Youngstown,
    Youngsville,
    Youngwood,
    Yukon
);
Z =     (
    Zelienople,
    Zieglerville,
    "Zion Grove",
    Zionhill,
    Zionsville,
    Zullinger
);

now, my table view loads with the correct number of sections, and rows within the sections and the indexing control works fine with this:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [cities count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if([searchArray count]==0)
     return @"";
    return [searchArray objectAtIndex:section];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[cities objectForKey:[searchArray objectAtIndex:section]] count];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    NSLog([NSString stringWithFormat:@"clicked index : %i",index]);
    if (index == 0) {
     [tableView scrollRectToVisible:[[tableView tableHeaderView] bounds] animated:NO];
     return -1;
    }
    return index;
}

My issue is now populating the text of the table cell with the text for each section...Any thoughts on how I can grab this info?

+1  A: 

Hi,

the cellForRowAtIndexPath gets a parameter of type NSIndexPath passed which contains both the required row and section. See NSIndexPath UIKit Additions for more details.

With that being said, this might work in your particular case:

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

  NSString *letter = [searchArray objectAtIndex:indexPath.section];
  NSArray *city = [cities objectForKey:letter];
  cell.text = [city objectAtIndex:indexPath.row];

  return cell;
}

Not sure if I got it right (haven't tried on a compiler), but you may get the general idea by now :)

Linas
Worked like a charm man. Saved a major headache for me. Thanks!
rson