Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
ma11hew28 Avatar asked Jun 20 '11 20:06

ma11hew28


2 Answers

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.

like image 56
Jonah Avatar answered Oct 14 '22 20:10

Jonah


The best practice for a UIView is to communicate with the ViewController using targets that can be defined from the ViewController by using (IBAction) for methods and (IBOutlets) for variables. Whenever the user makes any event with the view, it can alert the controller through these IBActions and the controller can (talk) to the view using the IBOutlets

like image 30
Ahmad Avatar answered Oct 14 '22 19:10

Ahmad