Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Delegates are a little hard to get used to, but I think it's the best practice and, like Apple, <em>they just work</em>.</p> <p>I always use the formal protocol declaration. It's a bit more logical in my mind, and it's very clear in the code. <strong>I suggest using a UIView to change your options instead of a controller. I always use one main controller and have a lot of subclassed UIViews that the one controller can control.</strong> (However, you can modify the following code for a controller, <strong>if you really need a controller instead of a normal view.</strong>) In the header file of the child view, make it look like this:</p> <pre><code>// ChildView.h #import &lt;UIKit/UIKit.h&gt; @protocol ChildViewDelegate; // tells the compiler that there will be a protocol definition later @interface ChildViewController : UIView { id &lt;ChildViewDelegate&gt; delegate; // more stuff } // properties and class/instance methods @end @protocol ChildViewDelegate // this is the formal definition - (void)childView:(ChildView *)c willDismissWithButtonIndex:(NSInteger)i; // change the part after (ChildView *)c to reflect the chosen options @end </code></pre> <p>The method between <code>@protocol</code> and the second <code>@end</code> can be called somewhere in the implementation of the ChildView, and then your root view controller can be the delegate that receives the 'notification.'</p> <p>The .m file should be like this:</p> <pre><code>// ChildView.m #import "ChildView.h" @implementation ChildView - (id)initWithDelegate:(id&lt;ChildViewDelegate&gt;)del { // make this whatever you want if (self = [super initWithFrame:CGRect(0, 0, 50, 50)]) { // if frame is a parameter for the init method, you can make that here, your choice delegate = del; // this defines what class listens to the 'notification' } return self; } // other methods // example: a method that will remove the subview - (void)dismiss { // tell the delegate (listener) that you're about to dismiss this view [delegate childView:self willDismissWithButtonIndex:3]; [self removeFromSuperView]; } @end </code></pre> <p>Then the root view controller's .h file would include the following code:</p> <pre><code>// RootViewController.h #import "ChildView.h" @interface RootViewController : UIViewController &lt;ChildViewDelegate&gt; { // stuff } // stuff @end </code></pre> <p>And the implementation file will implement the method defined in the protocol in ChildView.h, because it will run when the ChildView calls for it to be run. In that method, put the stuff that happens when you'd get the notification.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload