bertrandom bertrandom - 1 year ago 171
iOS Question

Get to UIViewController from UIView?

Is there a built-in way to get from a

to its
? I know you can get from
to its
[self view]
but I was wondering if there is a reverse reference?

pgb pgb
Answer Source

Since this has been the accepted answer for a long time, I feel I need to rectify it with a better answer.

Some comments on the need:

  • Your view should not need to access the view controller directly.
  • The view should instead be independent of the view controller, and be able to work in different contexts.
  • Should you need the view to interface in a way with the view controller, the recommended way, and what Apple does across Cocoa is to use the delegate pattern.

An example of how to implement it follows:

@protocol MyViewDelegate < NSObject >

- (void)viewActionHappened;


@interface MyView : UIView

@property (nonatomic, assign) MyViewDelegate delegate;


@interface MyViewController < MyViewDelegate >


The view interfaces with its delegate (as UITableView does, for instance) and it doesn't care if its implemented in the view controller or in any other class that you end up using.

My original answer follows: I don't recommend this, neither the rest of the answers where direct access to the view controller is achieved

There is no built-in way to do it. While you can get around it by adding a IBOutlet on the UIView and connecting these in Interface Builder, this is not recommended. The view should not know about the view controller. Instead, you should do as @Phil M suggests and create a protocol to be used as the delegate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download