user1238198
user1238198

Reputation: 71

UITableview Indexing with 1 section

I wonder if you can help me, I've read that it's possible to set up indexed scrolling, even if you have only 1 section in your table view. I have a lot of sorted table entries (over 50) and wish to jump to rows starting A, B, C, D etc as below - I'm pretty new to this and what I have is close, but it's not working properly - can you help ?

My code is as follows :-

enter code here 
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:@"A"];
[tempArray addObject:@"B"];
[tempArray addObject:@"C"];
[tempArray addObject:@"D"];
[tempArray addObject:@"F"];
[tempArray addObject:@"G"];
[tempArray addObject:@"H"];
[tempArray addObject:@"J"];
[tempArray addObject:@"K"];
[tempArray addObject:@"L"];
[tempArray addObject:@"M"];
[tempArray addObject:@"P"];
[tempArray addObject:@"S"];
[tempArray addObject:@"T"];
[tempArray addObject:@"U"];
[tempArray addObject:@"V"];    
return tempArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString     *)title atIndex:(NSInteger)index {

if(index !=0){ 
    [tableView scrollToRowAtIndexPath:[NSIndexPath
    indexPathForRow:index inSection:0] 
    atScrollPosition:UITableViewScrollPositionTop animated:TRUE];
}
return index;
}

Upvotes: 3

Views: 3011

Answers (1)

yibuyiqu
yibuyiqu

Reputation: 718

Do not return index. Just return 1, which is not a exist section index. Also, need to remove the if judgement. This makes the section scroll not working, then you can scroll to your own cell manually. I think you need to find the first match with selected alphabet, not just using the index to locate the cell.

To answer the comment below: It works perfect in my project. Here is my flow, hope it can help you: Assume you just have one section in that table.

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    // Find the correct index of cell should scroll to.
    int foundIndex = 0;
    for (Object *obj in dataArray) {
        if ([[[obj.YOURNAME substringToIndex:1] uppercaseString] compare:title] == NSOrderedSame || [[[obj.YOURNAME substringToIndex:1] uppercaseString] compare: title] == NSOrderedDescending)
            break;
        foundIndex++;
    }
    if(foundIndex >= [dataArray count])
        foundIndex = [dataArray count]-1;

    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

    return 1;
}

Upvotes: 5

Related Questions