8

I want to get the current view controller at present in page view controller. how it can be done. Does it have some delegate to call or what.

Pratik B
  • 1,599
  • 1
  • 15
  • 32
iPhone Programmatically
  • 1,211
  • 2
  • 22
  • 54
  • Maybe this can help http://stackoverflow.com/questions/8400870/uipageviewcontroller-return-the-current-visible-view – Mert Dec 14 '12 at 11:36

3 Answers3

25

I just had the same problem. Looks like the current controller is last in the list after you did change the page. This worked for me, but I don't know if it's always true.

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    UIViewController *vc = [pageViewController.viewControllers lastObject];
}
CodeStage
  • 540
  • 4
  • 6
  • @mnl what is failing? This worked for me, so if there's a bug I'd like to know =) – André Fratelli Nov 29 '14 at 21:10
  • This will work if I have go to another view than the beginning one and that's when that delegate is called, other than that the delegate will not help , If I have made no navigation at all – Mohamed Saleh Dec 13 '15 at 19:16
  • For this to work, you need to add UIPageViewControllerDelegate to your header file and also set the delegate with something like this in viewDidLoad: self.pageViewController.delegate=self; – JeffB6688 Feb 01 '17 at 16:26
2

Try get the first view controller in pageViewController.viewControllers

    if let vc = pageViewController.viewControllers?[0] {
        ... vc is current controller...
    }

If you want to handle page changes, do it in a delegate method:

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    if let vc = pageViewController.viewControllers?[0] {
        ... vc is current controller...
    }
}
0

if you are in any UIView class (as UIButton, UITable or any other subclass) that is a subView of the UIViewController.view (or of any subView.subView.subView... of it)

you can check if there's a UIViewController in the superVew(s) chain, and stop when you find a UIViewController

something like this:

UIViewController* controllerFound = nil;
for (UIView* next = [self superview]; next; next = next.superview) {
    UIResponder* nextResponder = [next nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        controllerFound = (UIViewController*)nextResponder;
    }
}
meronix
  • 6,175
  • 1
  • 23
  • 36