nilkash
nilkash

Reputation: 7536

Set navigation bar separator color IOS

Hi I am developing IOS application in which I tried to set navigation bar separator color in different ways but it's not working for me. I tried in following ways:

[self.navigationController.navigationBar.layer setBorderWidth:2.0];// Just to make sure its working
[self.navigationController.navigationBar.layer setBorderColor:[[UIColor redColor] CGColor]];

using above I can change border color of full navigation bar but I want to change just separator color only.

I tried another method:

 UIView *navBorder = [[UIView alloc] initWithFrame:CGRectMake(0,navBarCont.navigationBar.frame.size.height,navBarCont.navigationBar.frame.size.width, 1)];

[navBorder setBackgroundColor:[UIColor colorWithWhite:255.0f/255.f alpha:0.1f]];
[navBorder setOpaque:YES];

[navBarCont.navigationBar addSubview:navBorder];

This method work as I want but only thing is that when I rotate my device it will not change according to that. That mean if initially my device is in portrait mode it will show seperator in proper width but once I rotate my device to landscape it will not adjust width according to that.

So I tried to implement device orientation change listener also

 [[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(deviceOrientationDidChangeNotification:)
 name:UIDeviceOrientationDidChangeNotification
 object:nil];

 - (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
     [self setNavbar];
}

Above method causes one problem it keeps adding sublayer of separator view. So I have two options now one is put some auto layout constraints on added subview; or second one is every time remove old subview and then add new. But I dont know how to do that. Or is there any easy way to do this? Need some help. Thank you.

Upvotes: 0

Views: 2061

Answers (1)

michaelsnowden
michaelsnowden

Reputation: 6202

This provides a solution for not just any color, but also the height of the seperator:

- (void)viewDidLoad
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [self imageWithColor:[UIColor redColor] size:(CGSizeMake(self.view.frame.size.width, 1.0f))];
    self.navigationController.navigationBar.translucent = YES;
}

- (UIImage*) imageWithColor:(UIColor*)color size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    UIBezierPath* rPath = [UIBezierPath bezierPathWithRect:CGRectMake(0., 0., size.width, size.height)];
    [color setFill];
    [rPath fill];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Upvotes: 1

Related Questions