Search code examples
iosobjective-cuinavigationbarsubclassing

how to set navigationBar color by calling a method?


I created a CommonMethod subclass of NSObject for customizing UINavigationBar here is the CommonMethod.h and CommonMethod.m files

CommonMethod.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface CommonMethods : NSObject
+(void)setNavBackButton:(id)viewController;
+(void)setNavBackground:(id)viewController Color:(UIColor *)color;
@end

CommonMethod.h

#import <UIKit/UIKit.h>
#import "CommonMethods.h"
@implementation CommonMethods
+(void)setNavBackground:(id)viewController Color:(UIColor *)color
{
    UIViewController *controller = (id)viewController;
    controller.navigationController.navigationBar.backgroundColor=[UIColor redColor];
}
@end

Now when I am calling [CommonMethods setNavBackground:self Color:[UIColor redColor]; it is executing the method but didn't change anything on UI. Can anyone expalin this what I am missing ?

Edit :

I also tried controller.navigationController.navigationBar.barTintColor = color;


Solution

  • You have minor Mistake on Code

    +(void)setNavBackground:(id)viewController Color:(UIColor *)color
    {
        UIViewController *controller = (id)viewController;
        controller.navigationController.navigationBar.barTintColor = color; // Change NavigationBar color to Red
    }
    

    Call Method like this:[CommonMethod setNavBackground:self Color:[UIColor redColor]];

    enter image description here