scrollViewDidScroll is called "twice" after set table offset

1.3k views Asked by At

Hi everyone (and Merry Xmas)

hopefully someone could answer my question and that would be a great Christmas gift.

My UIViewController one table with a segmental control in the table section area. It looks like this enter image description here

each time when user click the segmental control, I will reload the table data and hopefully the table will show the correct position ( not exactly a row position, so i use table content offset ). here is my code:

- (void)clickSegmentedCenter code hereontrol:(int)index {
    self.firstTableOffset = 72;
    self.secondTableOffset = 250;
    self.thirdTableOffset = 600;

    CGFloat offset_y = 0;        
    switch (index) {
            case 0:
                offset_y = self.firstTableOffset;
                break;

            case 1:
                offset_y = self.secondTableOffset;
                break;

            case 2:
                offset_y = self.thirdTableOffset;
                break;
    }

    NSLog(@"[Debug] offset y is %f", offset_y);

    [self.tableView reloadData];
    self.tableView.contentOffset = CGPointMake(0, offset_y);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGPoint offset = scrollView.contentOffset;
    NSLog(@"[XXX] offset y is %f", offset.y);
}

The problem I got is, after table is reload data, it seems that I shouldn't call the self.tableView.contentOffset immediately. My table didn't scroll to the position as I set. And I found scrollViewDidScroll is called twice!!! the Log message looks like this:

enter image description here

So does anyone know what the correct way is to reload the table data and scroll the table to the specific position?? Thanks in advance.

Update: it turns out my code is correct. the reason is in my viewDidLoad, i set

self.tableView.estimatedRowHeight = 230.0;

And for some reason, this setting causes the problem. after I comment this line.. the behavior is correct. Originally I set my table's estimatedRowHeight is because my cell's height is dynamic. Now this problem is solved. Thanks for guys here for your advices. Merry Christmas !!!

1

There are 1 answers

0
Dheeraj D On

Could you please update scrollViewDidScroll like below and try:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    dispatch_async(dispatch_get_main_queue(), ^(void){
    CGPoint offset = scrollView.contentOffset;
    NSLog(@"[XXX] offset y is %f", offset.y);
    });
}