开发者

sectionIndexTitlesForTableView line up correctly with sections

I've got a table view with many sections, the title for these sections is just A-Z and # just like in the iPhone address book App. I have implemented sectionIndexTitlesForTableView to have the quick move to particular letter and basically just return an array of Letters A - Z and #.

This would work if my list always contains an item for every letter of the alphabet but it won't and this screws up the section index titles because hitting C in the list might go to D if the 3th section is D (ie if there is nothing in section C).

I know I could return the array in sectionIndexTitlesForTableView with only the letters that are sections but this would look a bit odd and not the same functionality as the iPhone Addre开发者_如何转开发ss book app.

How can I rectify this?


I don't see how @Rudiger's method would work if you have only have sections A, C, F, S, T and section index titles for A-Z. Such a situation might arise when using MPMediaQuery.

To get around this I've implemented this method as follows, the tableview will scroll to the correct section or the next if the one you are looking for doesn't exist.

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSString *sectionTitle = nil;
    NSComparisonResult result;
    int i;

    for(i = 0; i < tableView.numberOfSections; i++)
    {
        sectionTitle = [self tableView:tableView titleForHeaderInSection:i];
        result = [title compare:sectionTitle];

        if(result != NSOrderedDescending)
            break;
    }

    return (MIN (i, (tableView.numberOfSections - 1)));
}

UPDATE

Changed the return value to fix the situation described by Eric D'Souza.


Basically you have to implement:

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [sections indexOfObject:title];
}

and return based on the index and title what section it should be on. Where sections is the array storing the list of sections

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜