Pregunta

I've created a category on UIView that allows me to add a drop shadow to the view. My code for the shadow looks like this:

-(void)addDropShadowWithOffset:(CGFloat)offset {
    UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:self.bounds];
    self.layer.masksToBounds = NO;
    self.layer.shadowColor = [UIColor blackColor].CGColor;
    self.layer.shadowOffset = CGSizeMake(0.0f, offset);
    self.layer.shadowOpacity = 0.5f;
    self.layer.shadowPath = shadowPath.CGPath;
}

It works great. However, I've noticed that when I rotate the screen the shadow gets redrawn. The more I rotate it, the more the shadow is redrawn, leading to a shadow much larger than I originally wanted.

I originally thought about adding a BOOL iVar to the category that would let me track whether or not the shadow has already been drawn. But, it appears as though I can't add iVars to a category. So, how can I prevent this code from being run more than once per UIView? Any suggestions?

¿Fue útil?

Solución

I assume that you call it from method that is calling for every screen rotation (for example - layoutSubview) right? Method drawRect: and layoutSubviews are calling every time when you rotate the screen.

Move your method call to awakeFromNib method and should work fine.

EDIT:

Like you set in comment, if you building your interface from code, and using layoutSubviews to call shadow you may check if shadow is loaded with no additional bool flag. Just check:

-(void)layoutSubviews {
    [super layoutSubviews];

    if(!self.layer.shadowPath) {
        [self addDropShadowWithOffset:1.0];
    }
}

But, if you change size for example with rotation you may want to redraw the shadow after it. If you want to do this, just use the same mechanism as above.

EDIT2

Here is an idea. Maybe if you want to draw it only once you should override the initialiser. This is one-time call method.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top