Skip to content

Instantly share code, notes, and snippets.

@jacklynrose
Created March 16, 2014 14:45
Show Gist options
  • Save jacklynrose/9584278 to your computer and use it in GitHub Desktop.
Save jacklynrose/9584278 to your computer and use it in GitHub Desktop.
Monkey patch for finding the controller of a view
class UIView
def controller
if self.nextResponder.is_a? UIViewController
return self.nextResponder
elsif self.nextResponder.respond_to? :controller
return self.nextResponder.controller
end
end
end
@DanLuchi
Copy link

I've been using UIViewController.viewControllerForView to accomplish the same thing:

class UIView
  def controller
    controller_for_view(self)
  end

  def controller_for_view(view)
    controller = UIViewController.viewControllerForView view
    if controller
      controller
    elsif view.superview
      controller_for_view view.superview
    else
      nil
    end      
  end
end

In my app, Ive got a UIView inside a TPKeyboardAvoidingScrollView inside another UIView which is the root view, so I made my function recursive to allow for multiple levels of nesting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment