UITableView部分索引无法滚动到搜索栏索引

Min*_*sai 5 objective-c uitableview uisearchbar ios

在iOS7之前,我们在UITableView索引的顶部添加了一个放大镜图标,前面UITableViewIndexSearch是索引标题部分.

通过拖动到部分索引中的放大镜图标,tableView可以使用以下代码滚动到searchBar:

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

    NSInteger resultIndex = [self getSectionForSectionIndex:index];

    // if magnifying glass
    if (resultIndex == NSNotFound) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    else {
        return resultIndex;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是在iOS 7中,这只会滚动到第一部分而不是搜索栏.

Min*_*sai 9

为了解决这个问题,我们调整了内容偏移量以考虑iOS 7中引入的UITableView的内容插入: CGPointMake(0.0, -tableView.contentInset.top)

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

    NSInteger resultIndex = [self getSectionForSectionIndex:index];

    // if magnifying glass
    if (resultIndex == NSNotFound) {
        [tableView setContentOffset:CGPointMake(0.0, -tableView.contentInset.top)];
        return NSNotFound;
    }
    else {
        return resultIndex;
    }
}
Run Code Online (Sandbox Code Playgroud)