Skip to content

Instantly share code, notes, and snippets.

@chaitanyagupta
Forked from aprato/AMPNavigationBar.m
Last active December 25, 2015 18:59
Show Gist options
  • Save chaitanyagupta/7024530 to your computer and use it in GitHub Desktop.
Save chaitanyagupta/7024530 to your computer and use it in GitHub Desktop.
Use CGRectGetHeight() instead of accessing height directly.
// .h
@interface AMPNavigationBar : UINavigationBar
@property (nonatomic, assign) CGFloat extraColorLayerOpacity UI_APPEARANCE_SELECTOR;
@end
// .m
@interface AMPNavigationBar ()
@property (nonatomic, strong) CALayer *extraColorLayer;
@end
static CGFloat const kDefaultColorLayerOpacity = 0.5f;
@implementation AMPNavigationBar
- (void)setBarTintColor:(UIColor *)barTintColor
{
[super setBarTintColor:barTintColor];
if (self.extraColorLayer == nil) {
self.extraColorLayer = [CALayer layer];
self.extraColorLayer.opacity = self.extraColorLayerOpacity;
[self.layer addSublayer:self.extraColorLayer];
}
self.extraColorLayer.backgroundColor = barTintColor.CGColor;
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (self.extraColorLayer != nil) {
[self.extraColorLayer removeFromSuperlayer];
self.extraColorLayer.opacity = self.extraColorLayerOpacity;
[self.layer insertSublayer:self.extraColorLayer atIndex:1];
CGFloat spaceAboveBar = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
self.extraColorLayer.frame = CGRectMake(0, 0 - spaceAboveBar, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + spaceAboveBar);
}
}
- (void)setExtraColorLayerOpacity:(CGFloat)extraColorLayerOpacity
{
_extraColorLayerOpacity = extraColorLayerOpacity;
[self setNeedsLayout];
}
#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder];
if (self) {
_extraColorLayerOpacity = [[decoder decodeObjectForKey:@"extraColorLayerOpacity"] floatValue];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[super encodeWithCoder:encoder];
[encoder encodeObject:@(self.extraColorLayerOpacity) forKey:@"extraColorLayerOpacity"];
}
@end
// the easy way to use it is to subclass UINavigationController and override:
- (id)initWithRootViewController:(UIViewController *)rootViewController
{
self = [super initWithNavigationBarClass:[APNavigationBar class] toolbarClass:[UIToolbar class]];
if (self) {
self.viewControllers = @[ rootViewController ];
}
return self;
}
@kadimisetty
Copy link

It should be obvious, but if anyone is here from googling why use CGRectGetHeight etc. instead of accessing height/weight directly - It's because CGRect structures might store height and weight in negative values. (Documentation.)

@dmur
Copy link

dmur commented Mar 13, 2014

@kadimisetty awesome, thanks for adding that here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment