How to add a shadow effect for UINavigation bar

user1960169 picture user1960169 · Dec 8, 2015 · Viewed 10k times · Source

enter image description here

Hello, I want to add this kind of shadow for my NAvigationBar How can I do that.

This is how I tried to add shadow.

[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage=[UIImage new];

self.navigationController.navigationBar.translucent=YES;

self.navigationController.navigationBar.topItem.titleView.tintColor=[UIColor whiteColor];
self.navigationController.navigationBar.titleTextAttributes=[NSDictionary dictionaryWithObject:[UIFont fontWithName:@"HelveticaNeue" size:15.0f] forKey:NSFontAttributeName];
self.navigationController.navigationBar.topItem.title=strNavigtionTitle;
self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backarrow"] style:UIBarButtonItemStylePlain target:self action:@selector(revealToggle :)];
[self.navigationController navigationBar].tintColor = [UIColor whiteColor];

[self.navigationController navigationBar].layer.shadowColor=[UIColor colorWithRed:53.0/255.0 green:108.0/255.0 blue:130.0/255.0 alpha:1.0f].CGColor;
[self.navigationController navigationBar].layer.shadowOffset=CGSizeMake(0, 20);
[self.navigationController navigationBar].layer.shadowOpacity=0.8;
[self.navigationController navigationBar].layer.shadowRadius=5.5;

But this only add a shadow for the arrow and my Apply Leave title. But I want to add a drop shadow like in this image.It should be between the NavigationBar and my main UIView How can I do this? Please help me. Thanks

Answer

tania_S picture tania_S · Dec 8, 2015

Here you'll need to import the QuartzCore framework.

self.navigationController.navigationBar.layer.borderColor = [[UIColor whiteColor] CGColor];
self.navigationController.navigationBar.layer.borderWidth = 2; //Set border you can see the shadow 
self.navigationController.navigationBar.layer.shadowColor = [[UIColor blackColor] CGColor];
self.navigationController.navigationBar.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
self.navigationController.navigationBar.layer.shadowRadius = 3.0f;
self.navigationController.navigationBar.layer.shadowOpacity = 1.0f;
self.navigationController.navigationBar.layer.masksToBounds = NO;

Another thing You have to

set self.layer.masksToBounds = NO;

The default value for this property is YES, which means that even though the shadow is rendered, it won't be rendered outside the bounds of the view, which means effectively that you don't see it at all.

If you're animating this view in any way, you should also add this line:

self.layer.shouldRasterize = YES;