Search code examples
uiviewcalayerautolayout

Custom border for UIView using CALayer and autolayout


I have to draw a custom border for a UIView.

I already have code to do that but it was written before we started using autolayout.

The code basically adds a sublayer of width/height=1.0f

-(void)BordeIzquierdo:(UIColor *)pcColor cfloatTamanio:(CGFloat )pcfloatTamanio
{
    CALayer* clElemento = [self layer];
    CALayer *clDerecho = [CALayer layer];
    clDerecho.borderColor = [UIColor darkGrayColor].CGColor;
    clDerecho.borderWidth = pcfloatTamanio;
    clDerecho.frame = CGRectMake(0, 1, pcfloatTamanio, self.frame.size.height);
    [clDerecho setBorderColor:pcColor.CGColor];
    [clElemento addSublayer:clDerecho];
}

Now the problem is that with autolayout, this happens before layoutSubViews. So UIView.layer.frame is (0,0;0,0) and so the sublayer added is not shown because it has width/height=0.0f

Now how can I make this code without transferring this custom drawing to another method executed after viewDidLoad such as didLayoutSubviews.

I would like this styling to be correctly applied before viewDidLoad is called.

  • Is there anything like autolayout constraints that I can use with CALayers?
  • Any other ideas?

Solution

  • There is no CALayer autoresizing or constraints in iOS. (There is on Mac OS X, but no in iOS.)

    Your requirements here are unreasonable. You say that you refuse to move the call to BordeIzquierdo:. But you can't give clDerecho a correct size until you know the size of self (and therefore self.layer). Half the art of Cocoa touch programming is putting your code in the right place. You must find the right place to put the call to BordeIzquierdo: so that the values you need have meaning at the moment it is called.

    What I would do is put it in layoutSubviews along with a BOOL flag so that you only do it once.