title: How to draw inside a layer and add to context only after [viewLayer addSublayer:newLayer]?
body: <h2>The question</h2>
  <p>How do you create a separate context for your layer and incorporate that context into super layer?</p>
  <h2>Why I want to do this</h2>
  <p>I want abstract the drawing of a view layers into separate objects/files. I want to construct a view out of layers, then position then on top of one another and have other possibilities as that.</p>
  <p>The problem is that I'm not aware of you you're supposed to draw a part of your view into a layer <strong>without</strong> drawing straight into the context of the main views sublayer.</p>
  <p>Here's an example, I have subclassed <code>CALayer</code> with <code>HFFoundation</code>:</p>
  <pre><code>@implementation HFFoundation
  
  - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
      UIBezierPath *foundation = [UIBezierPath bezierPath];
      // some drawing goes on here in the form of messages to [foundation]
  }
  
  @end
  </code></pre>
  <p>Now when I instantiate my custom layer inside a views <code>(void)drawRect:(CGRect)rect</code> I this way:</p>
  <pre><code>HFFoundation *foundation = [HFFoundation new];
  foundation.frame = CGRectMake(40, viewHeight - 100, 300, 100);
  foundation.backgroundColor = [[UIColor colorWithRed:1 green:.4 blue:1 alpha:0.2] CGColor];
  
  [self.window.rootViewController.view.layer addSublayer:foundation];
  </code></pre>
  <p>I get this result (no drawings appear, just the bg color inside the layer frame):</p>
  <p><img src="https://i.stack.imgur.com/siaep.png" alt="adding a sublayer" /></p>
  <p>If I <code>[foundation drawLayer:foundation inContext:context];</code> afterwards, the drawing appears, but it appears inside the top layers context, not in <code>foundation</code> layer. Since <code>foundation</code> layer is also lower in the hierarchy, it hides the drawing (unless I reduce it's alpha, which I've dont in the picture):</p>
  <p><img src="https://dl.dropboxusercontent.com/u/31042440/stackoverflow/layer-moved-up.png" alt="it draws straight into the context" /></p>
  <p>How do you draw into the layer itself, I.e. <code>foundation</code> in this case?</p>