Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autolayout and shadow

I've got a problem with adding shadow to my UIView which is created in iOS 6 application with Autolayout.

Let's assume I have a method that adds a shadow on the bottom of UIView (this is actually a Category of UIView, so it's reusable):

- (void) addShadowOnBottom {
    self.layer.shadowOffset = CGSizeMake(0, 2);
    self.layer.shadowOpacity = 0.7;
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
}

When I call this method in viewDidLoad of some UIViewController, shadow is not added, probably due to all constraints, that have to be calculated.

When I call this method in viewWillAppear the same situation.

When I call this method in viewDidAppear it works, but when new view shows up there is a short moment when there is no shadow and it appears after a while.

If I resign from setting the shadowPath and remove line self.layer.shadowPath everything works, but view transitions are not smooth.

So my question is what is the right way to add a shadow to view in iOS 6 with Autolayout turned on ?

like image 662
Kamil Avatar asked Jan 25 '13 18:01

Kamil


2 Answers

i removed self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath; from your code and it is working for me in viewDidLoad, please confirm.

Increasing shdowOffset will make you see the shadow more clear.

like image 172
Vaibhav Saran Avatar answered Nov 18 '22 18:11

Vaibhav Saran


Another thing you can add to the layer when working with AutoLayout and you need a shadow on a UIView where the frame is not yet known is this :

self.layer.rasterizationScale = [[UIScreen mainScreen] scale]; // to define retina or not
self.layer.shouldRasterize = YES;

Then remove the shadowPath property because the auto layout constraints are not yet processed, so it's irrelevant. Also at the time of execution you will not know the bounds or the frame of the view.

This improves performance a lot!

like image 15
Yannick Avatar answered Nov 18 '22 17:11

Yannick