开发者

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 UIControls I would like to send a message to my custom view controller.

Currently I can see two solutions for this:

  1. 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)
  2. The UIControl could send an NSNotification (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.

  1. Assign a value to the tag property of the control, then access it using viewWithTag: from the view controller when you are setting up it's target-action events.
  2. Provide public accessors on each UIView subclass for each subview, then access the control from the view controller using these properties.
  3. 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.
  4. 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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜