abhimuralidharan
abhimuralidharan

Reputation: 5939

How to create a custom class to add shadow to UINavigationBar IOS

I need to make a custom class with the following code to set shadow to UINavigationBar in iOS.

@interface UINavigationBar (CustomImage)

-(void) applyDefaultStyle;

@end
@implementation UINavigationBar (DropShadow)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"titleBar.png"];
    [image drawInRect:CGRectMake(0, 0, 320, 44)];
}

-(void)willMoveToWindow:(UIWindow *)newWindow{
    [super willMoveToWindow:newWindow];
    [self applyDefaultStyle];
}

- (void)applyDefaultStyle {
    // add the drop shadow
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowOffset = CGSizeMake(0.0, 3);
    self.layer.shadowOpacity = 0.25;
    self.layer.masksToBounds = NO;
    self.layer.shouldRasterize = YES;
}@end

How can I do that?

Also, the above code adds shadow to each and every navigationbar in my app. How to control this? I need shadow only on one or two navigationBars.

Upvotes: 0

Views: 356

Answers (2)

You have implemented Category for UINavigationBar, Which will affect all UINavigationBar & It's Custom UINavigationBar(Subclass of UINavigationBar).

If you want this behaviour on only selected navigation bars, Then you can adopt the Inheritance(Subclass) of UINavigationBar.

Take a look at this tutorial 1

Tutorial 2

Upvotes: 1

Steve Wilford
Steve Wilford

Reputation: 9002

The reason that every UINavigationBar is affected is because the code you have creates a category and modifies the existing class.

You would need to change the category to be a subclass:

@interface CustomNavigationBar : UINavigationBar
...
@end

@implementation CustomNavigationBar
...
@end

Then you can use the UINavigationController initWithNavigationBarClass:toolbarClass: and provide the CustomNavigationBar class on the navigation controllers you wish to affect:

UINavigationController *navController = [[UINavigationController alloc] initWithNavigationBarClass:[CustomNavigationBar class]
                                                                                      toolbarClass:nil];

// Make sure to provide a root view controller
[navController setViewControllers:@[rootViewController] animated:NO];

Upvotes: 1

Related Questions