我在表格视图中显示一个动态名称列表,我正在尝试根据名称的第一个字母将它们分成几个部分......
我创建了一个按字母顺序排列的字母列表
charIndex = [[NSMutableArray alloc] init];
for(int i=0; i<[appDelegate.children count]-1; i++)
{
// get the person
Child *aChild = [appDelegate.children objectAtIndex:i];
// get the first letter of the first name
NSString *firstLetter = [aChild.firstName substringToIndex:1];
NSLog(@"first letter: %@", firstLetter);
// if the index doesn't contain the letter
if(![charIndex containsObject:firstLetter])
{
// then add it to the index
NSLog(@"adding: %@", firstLetter);
[charIndex addObject:firstLetter];
}
}
我已经设置了部分和标题的数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// set the number of sections in the table to match the number of first letters
return [charIndex count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// set the section title to the matching letter
return [charIndex objectAtIndex:section];
}
但是我在
中应该遇到什么问题- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
}
答案 0 :(得分:4)
您可以添加一个字典,用于跟踪共享相同首字母的人数。快速未经测试的代码:
charIndex = [[NSMutableArray alloc] init];
charCount = [[NSMutableDictionary alloc] init];
for(int i=0; i<[appDelegate.children count]-1; i++)
{
// get the person
Child *aChild = [appDelegate.children objectAtIndex:i];
// get the first letter of the first name
NSString *firstLetter = [aChild.firstName substringToIndex:1];
NSLog(@"first letter: %@", firstLetter);
// if the index doesn't contain the letter
if(![charIndex containsObject:firstLetter])
{
// then add it to the index
NSLog(@"adding: %@", firstLetter);
[charIndex addObject:firstLetter];
[charCount setObject:[NSNumber numberWithInt:1] forKey:firstLetter];
}
[charCount setObject:[NSNumber numberWithInt:[[charCount objectForKey:firstLetter] intValue] + 1] forKey:firstLetter];
}
然后在:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
[charCount objectForKey:[charIndex objectAtIndex:section]];
}