Search code examples
uitextviewsuperview

How do I get a UIViewController given a UITextView?


I'm handling code in a UITextViewDelegate. Each function there receives the UITextView instance that received the event, for example:

- (void)textViewDidBeginEditing:(UITextView*)textView
{

}

Inside that method however, only given the textView, I need to access the UIViewController that contains the textView.

Using textView.superview (even multiple stages of it) doesn't seem to work - I only get:

  • textView.superview = an instance of UIView
  • textView.superview.superview = UIViewControllerWrapperView
  • textView.superview.superview.superview = UINavigationTransitionView
  • textView.superview.superview.superview.superview = UILayoutContainerView
  • textView.superview.superview.superview.superview.superview = UIWindow
  • textView.superview.superview.superview.superview.superview.superview = nil

I found the class names by printing out something like

printf( "class: %s\n", [[[uiv class] description] UTF8String] ) ;

Solution

  • There is no way to do this. A UIViewController knows what UIView it manages, but a view does not have a reference back to its view controller (and might not even have a view controller).

    The -superview method returns another UIView, which is not the same thing as a UIViewController.

    Why do you need the view controller? What are you trying to accomplish?

    As an aside, you could save yourself a few keystrokes by using NSLog instead of printf:

    NSLog(@"class: %@", [uiv class]);