RGriffiths
RGriffiths

Reputation: 5970

UITableView scroll section to the top when touched

I have a table view with a number of sections. When the section header is touched it expands:

enter image description here

What I would like is for the section header touched to scroll to the top of the table view:

enter image description here

Here is the code I have tried. The expanding/collapsing works fine but the section does not scroll to the top. I imagine scrollRectToVisible:sectionRect simply makes the section visible in the view. How can I get it to scroll to the top?

- (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];
}

Upvotes: 0

Views: 62

Answers (1)

R4N
R4N

Reputation: 2595

Perhaps scrollToRowAtIndexPath:scrollPosition:animated will do trick?

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

Passing in an index path of NSNotFound for row and the target section you'd like to scroll to:

// 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];

Upvotes: 1

Related Questions