Iphone : How to scroll to the 1st cell of the 2nd

2019-04-13 01:33发布

问题:

I have an UITableView with rows and sections. I would like to scroll to the first item of the second section, letting the header of the first section visible. Like if I had manually scrolled the list until reaching that state.

---- TOP OF SCREEN ----
Header of first section
Header of the second section
cell 1
cell 2
cell 3
Header of the third section
cell 1
cell 2
...

scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] does not do the job, it hides the header of the first section.

回答1:

We're moving on. I found this method based on Kevin's idea. To be able to set animated to YES, I catch the end of animation using a delegate method of UIScrollView. It works. But any solution that would help not doing 2 animations would be greatly appreciated. Any idea about how to do this ?

- (IBAction) scrollToToday:(BOOL)animate {
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:animate];
    if (animate == NO) [self showFirstHeaderLine:NO];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self showFirstHeaderLine:YES];
}

- (void) showFirstHeaderLine:(BOOL)animate {
    CGRect headerRect = [self.tableView rectForHeaderInSection:1];
    CGPoint scrollPoint = headerRect.origin;
    scrollPoint.y -= headerRect.size.height;
    [self.tableView setContentOffset:scrollPoint animated:animate];
}

Dude to this code, the process when animated is set to YES should loop infinitely beetween scrollViewDidEndScrollingAnimation and showFirstHeaderLine... It loops, yes, but only once... Any idea about why ?



回答2:

You can grab the rect for the row you want, then subtract the height of the header of the previous section and scroll to that point. Something like the following (untested) should work:

CGRect rowRect = [table rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
CGRect headerRect = [table rectForHeaderInSection:0];
rowRect.origin.y -= headerRect.size.height;
rowRect.size.height += headerRect.size.height;
[table scrollRectToVisible:rowRect animated:YES]; // UITableView is a subclass of UIScrollView


回答3:

I tried your code, and it works!!

For the loop question, since you are setting a offset(SetContentOffset), it has nothing to do with the scroll. It is will not call scrollView delegate. SO the scrollViewDidEndScrollingAnimation will be called only once, which has been called from scrollToRowAtIndexPath.