2013-07-16 27 views
0

我有一个UITableView使用按字母顺序滚动,但是当我选择特定字母时,它没有做。作为示例,如果我选择“G”它不跳到“G”它只是滚动26个字母为什么如此。UITableView按字母顺序滚动问题当特定字母选项卡

我的代码

alphabetical =[NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil]; 


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 

    return alphabetical; 
} 
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 

    NSInteger newRow = [self indexForFirstChar:title inArray:alphabetical]; 
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:newRow inSection:0]; 
    [tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO]; 

    return index; 
} 

- (NSInteger)indexForFirstChar:(NSString *)character inArray:(NSArray *)array 
{ 
    NSUInteger count = 0; 
    for (NSString *str in array) { 
     if ([str hasPrefix:character]) { 
      return count; 
     } 
     count++; 
    } 
    return 0; 
} 

我认为有些事情我indexForFirstChar是错误的,当我添加有断点它只是要扔掉所有的字母和它不是跳跃到一个特定的..

我没有在这个表格查看

感谢您的帮助和快速的回​​答!

回答

0

我被我自己解决其非常简单,或多或少不需要评论它是如何工作的

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { 
    if (alphabetical) 
    { 
     NSMutableArray *charactersForSort = [[NSMutableArray alloc] init]; 
     for (NSDictionary *item in employees) 
     { 
      if (![charactersForSort containsObject:[[item valueForKey:@"LastName"] substringToIndex:1]]) 
      { 
       [charactersForSort addObject:[[item valueForKey:@"LastName"] substringToIndex:1]]; 
      } 
     } 
     return charactersForSort; 
    } 
    return nil; 
} 

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { 
    BOOL found = NO; 
    NSInteger b = 0; 
    for (NSDictionary *item in employees) 
    { 
     if ([[[item valueForKey:@"LastName"] substringToIndex:1] isEqualToString:title]) 
      if (!found) 
      { 
       [_tblPersonDetail scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:b inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; 
       found = YES; 
       break; 
      } 
     b++; 
    } 
    return b; 
} 

如果你仍然有一些问题请随时问

0

无需滚动到sectionForSectionIndexTitle中的索引路径。只需返回index即可。请参阅documentation

而且,这里是你一个小窍门:

alphabetical = [@"ABCDEFGHIJKLMNOPQRSTUVWXYZ" componentsSeparatedByString:@""]; 
+0

感谢提示gj ^^,但是我已经在'sectionForSectionIndexTitle'中重新调整索引或者? – Mingebag

+0

是的,但你也在用这种方法滚动 - 不要。 – Mundi

+0

我不使用该表中的部分视图也许这将有助于 – Mingebag