0

My UITableView needs to scroll all the way to the top after popping back to ViewController under certain circumstances.

The code below works fine (I edited it for simplicity), but I am hoping to find a better way without using a delay timer. If I don't use a timer the UITableView doesn't scroll all the way to the top because the ViewController hasn't loaded yet (I think).

DetailController.m

- (void)popToViewController {
    // pop back to ViewController.
    [self.navigationController popViewControllerAnimated:YES];

    // Calls ViewController method
    [self.viewController method];
}

ViewController.m

- (void)method {
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self.tableView setContentOffset:CGPointZero animated:NO];
        });
}

I tried using ViewDidAppear in ViewController and it works, but it gets called all the time if I pop the ViewController. I only need to scroll the UITableView all the way up under certain circumstances.

Edit: I also tried dispatch_async, but it doesn't work all the time.

Gaurav Patel
  • 532
  • 1
  • 5
  • 19
Curt Rand
  • 1,025
  • 1
  • 9
  • 27
  • Use a delegate method going back from detailVC to masterVC. There you can pass a parameter with the conditions and then in masterVC you can decide to scroll or not. – koen Jun 05 '18 at 19:35
  • Possible duplicate of [UITableView - scroll to the top](https://stackoverflow.com/questions/724892/uitableview-scroll-to-the-top) – Will Jones Jun 05 '18 at 19:53

1 Answers1

0

It is possible to add a completion block for the animation. Remove your timer and try something like this:

- (void)popToViewController {
    [CATransaction begin];

    [CATransaction setCompletionBlock:^{
        [self.viewController method];
    }];

    [self.navigationController popViewControllerAnimated:YES];

    [CATransaction commit];
}
Edudjr
  • 1,676
  • 18
  • 28