Search code examples
iosobjective-cuinavigationcontrollerviewdidload

Navigation Styling throughout app


is there a way to implement the below code for the styling of my navigation bar in ViewDidLoad or globally somehow, instead of pasting in every VC? Thanks.

// Navagation styling
    viewController.title = @"NAV TITLE";
    [viewController.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Gibson-Light" size:20.0], NSFontAttributeName, nil]];

    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithTitle:nil
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:viewController
                                                                      action:nil];

    rightBarButton.image = [UIImage imageNamed:@"settings_cog"];
    rightBarButton.tintColor = [UIColor grayColor];

    viewController.navigationItem.rightBarButtonItem = rightBarButton;

Solution

  • You can create a BaseViewController and put the above code in it and extend all your controllers from the BaseViewController.

    Do like this:

    Create an Objective-C class BaseViewController.h and .m

    In BaseViewController.h

    @interface BaseViewController : UIViewController
    {
        NSString *_title;
    }
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil title:(NSString *)navTitle;    
    
    @end
    

    In BaseViewController.m

    @implementation BaseViewController
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil title:(NSString *)navTitle
    {
        _title = navTitle;
    }
    
    - (void)viewDidLoad
    {
        self.title = _title;
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"Gibson-Light" size:20.0], NSFontAttributeName, nil]];
        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithTitle:nil
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:viewController
                                                                      action:nil];
        rightBarButton.image = [UIImage imageNamed:@"settings_cog"];
        rightBarButton.tintColor = [UIColor grayColor];
        self.navigationItem.rightBarButtonItem = rightBarButton;
    }
    
    @end
    

    Now you can create your view controller and extend it from BaseViewController instead if UIViewController.

    Let me know if you have any questions.