Best way to send a message to a View Controller from a deeply nested UIControl?
I have the following structure in my app:
Custom开发者_Go百科 View Controller
+- Custom View 1
+- Custom View 2
+- A number of UIControls
If the user taps one of the UIControl
s I would like to send a message to my custom view controller.
Currently I can see two solutions for this:
- Tell the 1st custom view about the controller, then tell the 2nd custom view about it as well, and set the target and action when I create the 'UIControl's. (My custom views could have a -initWithFrame:controller: method or something)
- The
UIControl
could send anNSNotification
(possibly with some userInfo) that my controller observes.
I'm leaning toward option 2 because I dislike telling Custom View 1 about my controller, just so it can tell Custom View 2 about it.
What are the pros and cons for my two solutions, or is there another way to do this?
Update: I went with the NSNotification
for now.
How about you keep a pointer to your Custom View Controller from your app delegate and expose it as a property.
Then you can use the static sharedApplication message on UIApplication to get to your app delegate and the corresponding property:
// in custom view 2 code ...
YourApplication * app = (YourApplication*)[UIApplication sharedApplication];
CustomViewController * cvc = app.customViewController;
There are several possibilities but the best one really depends on your particular business case, and the purposes of several nested UIView subclasses.
- Assign a value to the
tag
property of the control, then access it usingviewWithTag:
from the view controller when you are setting up it's target-action events. - Provide public accessors on each UIView subclass for each subview, then access the control from the view controller using these properties.
- Use the responder chain. Specify a nil target when setting up the control's target-action and the action will eventually be sent to the view controller if it implements it.
- Depending on the nature of your UIView subclasses, it might be better to implement any necessary callbacks to the view controller through a delegate protocol of the view. So the target-action of the control would be assigned by the containing UIView subclass to itself, and in it's handler it would call it's own delegate method.
精彩评论