如何滚动到分组样式UITableView的第一行?

时间:2014-04-18 00:50:44

标签: uitableview

我有一个分组样式UITableView,我想滚动到每个部分的第一行。我使用以下代码,但这会将我带到节标题。有没有办法转到行的顶部?

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]
                             atScrollPosition:UITableViewScrollPositionTop animated:YES];

2 个答案:

答案 0 :(得分:0)

也许您可以使用scrollRectToVisible代替。像这样

CGRect rect = CGRectMake(0.f,
                         yOfTargetCell, //Calc first
                         self.tableView.frame.size.width,
                         self.tableView.frame.size.height);
[self.tableView scrollRectToVisible:rect animated:YES];

答案 1 :(得分:0)

我最终使用contentInsets来实现这一目标:

- (void)jumpToSection:(NSUInteger)section {

    self.autoscrolling = YES;

            // inset the table, so that the section header is hidden when auto-scrolling
            // between sections
            [self.tableView setContentInset:UIEdgeInsetsMake(-sectionHeaderHeight,0,0,0)];


            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]
                                  atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

    if (self.autoscrolling) {
        [self removeInsets];
    }

    self.autoscrolling = NO;
}

- (void)removeInsets {
    // remove inset so that all section headers are visible when
    // when scrolling manually
    [self.tableView setContentInset:UIEdgeInsetsMake(0,0,0,0)];
}