model-view-controlleruiviewdelegatesuiviewcontrolleruikit

Should a UIView reference its UIViewController?


Some answers say that Get to UIViewController from UIView? is a bad design practice.

But, LevelView, from Apple's very own BubbleLevel Xcode example project, has an assign property to its viewController.

I think the best thing to do is to define a protocol & assign the view controller as the delegate of the view, like you would do with a UITableView or a UITextField or UITextView.

But, I could be wrong, so my question is what is the recommended way for a view to communicate with its view controller?


Solution

  • Delegation (using a weak reference) is a fine way for a view to communicate with a controller. However your view should not need to be aware that it is communicating with a controller. The view should only know that some object exists which implements its delegate protocol and not need to traverse the controller hierarchy or use any attributes of its delegate which are not defined in the delegate protocol.

    This allows the views to remain very loosely coupled to their controllers. You should be able to switch which object acts as a view's delegate or change which controller is presenting that view without ever changing the view itself.