触摸时 UITableView 滚动部分到顶部

时间:2021-04-15 13:14:28

标签: objective-c uitableview

我有一个包含多个部分的表格视图。当部分标题被触摸时,它会展开:

enter image description here

我想要的是触摸部分标题以滚动到表格视图的顶部:

enter image description here

这是我试过的代码。展开/折叠工作正常,但该部分不会滚动到顶部。我想 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];
}

1 个答案:

答案 0 :(得分:1)

也许 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];
相关问题