UITableView 触摸时将部分滚动到顶部

UITableView scroll section to the top when touched

我有一个包含多个部分的 table 视图。触摸 header 部分时,它会展开:

我想要的是 header 部分滚动到 table 视图的顶部:

这是我试过的代码。 expanding/collapsing 工作正常,但该部分不会滚动到顶部。我想 scrollRectToVisible:sectionRect 只是让该部分在视图中可见。我怎样才能让它滚动到顶部?

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {

    ... adding the content of the header

    // To make header touchable
    header.tag = section;
    UITapGestureRecognizer *headerTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTouched:)];
    [header addGestureRecognizer:headerTapGesture];
}

- (void)sectionHeaderTouched:(UITapGestureRecognizer *)sender {

    ... all the code to handle the expanding / collapsing
    
    // Scroll section to top
    CGRect sectionRect = [standardsTableView rectForSection:section];
    sectionRect.size.height = standardsTableView.frame.size.height;
    [standardsTableView scrollRectToVisible:sectionRect animated:YES];
}

也许scrollToRowAtIndexPath:scrollPosition:animated会耍花招?

https://developer.apple.com/documentation/uikit/uitableview/1614997-scrolltorowatindexpath

为行和要滚动到的目标部分传入 NSNotFound 的索引路径:

// section 6 just an example here, replace with the target section instead
NSIndexPath *topOfSection = [NSIndexPath indexPathForRow:NSNotFound inSection:6];
[self.tableView scrollToRowAtIndexPath:topOfSection atScrollPosition:UITableViewScrollPositionTop animated:YES];