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

2019-04-13 01:39发布

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.

3条回答
SAY GOODBYE
2楼-- · 2019-04-13 02:05

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 ?

查看更多
▲ chillily
3楼-- · 2019-04-13 02:07

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
查看更多
贪生不怕死
4楼-- · 2019-04-13 02:12

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.

查看更多
登录 后发表回答