4

I have a UIAlertView. When the user taps a button in the alert view I want to show a new UIViewController.

In order to achieve this I need to know which view controller is currently visible on screen because that particular view controller is the right one to present the new view controller.

The problem is that I have a complex hierarchy of view controllers in my app including a UINavigationController and a UITabBarController (among others). So I cannot simply use self.visibleViewController to get the currently visible view controller.

I have found a possible solution on Stackoverflow but I would like to find a neater solution without having to dig through the whole view controller stack.

Community
  • 1
  • 1
Mischa
  • 15,816
  • 8
  • 59
  • 117
  • 1
    I'm not sure if this works or not, I haven't tested it but if you're creating a UIAlertView and presenting it within the last visible UIViewController, doesn't that mean the "delegate" of that UIAlertView is your last visible view controller? – Zhang Aug 19 '13 at 12:17
  • I am a bit confused. You must have set the code for UIAlertView somewhere. On which ViewController you have set that? – Puneet Sharma Aug 19 '13 at 12:21
  • The delegate of a `UIAlertView` is not necessarily a `UIViewController`. It can be any class that conforms to the `UIAlertViewDelegate` protocol. In my case the delegate is actually a `UIViewController` but it is a specific one that is not always visible. – Mischa Aug 19 '13 at 12:28
  • 1
    @Puneet: A `UIAlertView` is not necessarily presented by a specific `UIViewController`. Instead, I use `[alertView show]`. I can call that method from anywhere in my code because a [UIAlertView always creates its own window](http://stackoverflow.com/a/3727470/2062785). – Mischa Aug 19 '13 at 12:39

1 Answers1

5

UINavigationController has a property called topViewController. Maybe it helps you.

chris13
  • 640
  • 5
  • 14