Home > beginner > Custom Navigation Bar View Implementation

Custom Navigation Bar View Implementation

June 11Hits:4
Advertisement

In one of my app, i m using custom navigation bar view to handle all Navigation Bar Properties.

Is it good practice to use custom navigation in given below way? Any Optimizations need to be done. It would be helpful to me, if you have any valuable suggestions.

Source Code ---->

.h

#import <UIKit/UIKit.h>  @protocol VCNavigationBarViewDelegate <NSObject> @optional  - (void)menuButtonPressed; - (void)backButtonPressed; - (void)cancelButtonPressed; - (void)filterButonApplyPressed; - (void)NotificationButtonPressed; @end  typedef enum {   NavigationStyleLeftMenu = 0,   NavigationStyleBackButton,   NavigationStyleCancelButton,   NavigationStyleSearch,   NavigationStyleFilter,   NavigationStyleEmpty,   NavigationStyleNotification } NavigationStyle;  @interface VCNavigationBarView : UIView   @property (weak, nonatomic) IBOutlet UIImageView *imgLogoConnect;  @property (weak, nonatomic) IBOutlet UIButton *btnMenu;  @property (weak, nonatomic) IBOutlet UIButton *btnBack;  @property (weak, nonatomic) IBOutlet UIButton *btnCancel;  @property (weak, nonatomic) IBOutlet UIButton *btnFilterApply;  @property (weak, nonatomic) IBOutlet UIButton *btnFilterCancel;  @property (weak, nonatomic) IBOutlet UILabel  *lblHeaderTitle;  @property (weak, nonatomic) IBOutlet UIButton *btnNotification;  @property (weak, nonatomic) id <VCNavigationBarViewDelegate> navigationDelegate;  - (IBAction)btnBackAction:(id)sender; - (IBAction)btnMenuAction:(id)sender; - (IBAction)btnCancelction:(id)sender; - (IBAction)btnFilterApplyAction:(id)sender; - (IBAction)btnNotificationAction:(id)sender;  - (void)configureWithStyle:(NavigationStyle)navigationStyle;  @end 

.m

#import "VCNavigationBarView.h" @implementation VCNavigationBarView  - (void)configureWithStyle:(NavigationStyle)navigationStyle  {    self.btnFilterApply.hidden = YES;    self.btnFilterCancel.hidden = YES;    self.btnBack.hidden = YES;    self.btnCancel.hidden = YES;    self.btnMenu.hidden = YES;    self.lblHeaderTitle.hidden = YES;    self.btnNotification.hidden = YES;    self.imgLogoConnect.hidden = YES;  switch(navigationStyle) {     case NavigationStyleLeftMenu:     {         self.btnMenu.hidden = NO;         self.btnNotification.hidden = NO;         self.imgLogoConnect.hidden = NO;     }         break;      case NavigationStyleBackButton:     {         self.lblHeaderTitle.hidden = NO;         self.btnBack.hidden = NO;     }         break;      case NavigationStyleCancelButton:     {         self.lblHeaderTitle.hidden = NO;         self.btnCancel.hidden = NO;     }         break;      case NavigationStyleSearch:     {         self.btnCancel.hidden = NO;     }         break;      case NavigationStyleFilter:     {         self.lblHeaderTitle.hidden = NO;         self.btnFilterApply.hidden = NO;         self.btnFilterCancel.hidden = NO;         self.backgroundColor = [UIColor colorWithRed:76.0/255 green:76.0/255 blue:76.0/255 alpha:1.0];     }         break;      case NavigationStyleEmpty:     {         self.lblHeaderTitle.hidden = NO;     }         break;      case NavigationStyleNotification:     {         self.lblHeaderTitle.hidden = NO;         self.btnBack.hidden = NO;     }         break;    } }  - (IBAction)btnBackAction:(id)sender { if ([self.navigationDelegate respondsToSelector:@selector(backButtonPressed)]) {     [self.navigationDelegate backButtonPressed];     } }  - (IBAction)btnMenuAction:(id)sender{ if([self.navigationDelegate respondsToSelector:@selector(menuButtonPressed)])     [self.navigationDelegate menuButtonPressed]; }  - (IBAction)btnCancelction:(id)sender{ if([self.navigationDelegate respondsToSelector:@selector(cancelButtonPressed)])     [self.navigationDelegate cancelButtonPressed]; }  - (IBAction)btnFilterApplyAction:(id)sender{ if([self.navigationDelegate respondsToSelector:@selector(filterButonApplyPressed)])     [self.navigationDelegate filterButonApplyPressed]; }  - (IBAction)btnNotificationAction:(id)sender{ if([self.navigationDelegate respondsToSelector:@selector(NotificationButtonPressed)])     [self.navigationDelegate NotificationButtonPressed]; } @end 

In BaseViewController, All Other View Controller inherited from BaseViewController

BaseVC.h

@interface VCBaseViewController : UIViewController<VCNavigationBarViewDelegate>  @property (strong, nonatomic) IBOutlet UIView *navigationBarView;  - (void)configureNavigationBarWithStyle:(NavigationStyle)style; - (void)setViewControllerTitle:(NSString *) title; 

BaseVC.m

navigationBar Configuraion

 - (void)configureNavigationBarWithStyle:(NavigationStyle)style {    CGRect frame;    NSArray *nibItems = [[NSBundle mainBundle] loadNibNamed:@"VCNavigationBarView" owner:nil options:nil];    self.menuNavigationBarView = [nibItems firstObject];    self.menuNavigationBarView.navigationDelegate = self;    [self.menuNavigationBarView configureWithStyle:style];    frame = self.navigationBarView.frame;    frame.origin.y = 20.0;    self.navigationBarView.frame = frame;     [self.navigationBarView addSubview:self.menuNavigationBarView];    NSArray *subConstraints;    NSDictionary *viewsDictionary = @{@"menuNavigationBarView" : self.menuNavigationBarView };    self.menuNavigationBarView.translatesAutoresizingMaskIntoConstraints = NO;  // Set left & right constraints to the container view  subConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[menuNavigationBarView]|"                                                          options:0                                                          metrics:nil                                                            views:viewsDictionary]; [self.navigationBarView addConstraints:subConstraints];   // Set left & right constraints to the container view  subConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[menuNavigationBarView]|"                                                          options:0                                                          metrics:nil                                                            views:viewsDictionary]; [self.navigationBarView addConstraints:subConstraints]; }  - (void) setViewControllerTitle:(NSString *) title {   [self.menuNavigationBarView.lblHeaderTitle setText:title]; } 

In Child/Inherited View Controller from BaseViewController

.m

- (void)viewDidLoad {  [super viewDidLoad];  [self configureNavigationBarWithStyle:NavigationStyleBackButton];  [self setViewControllerTitle:@"My Orders"]; } 

Answers

There are piles of formatting problems in this code which should be the first thing you strive to fix.


You have inconsistent brace styles.

Your IBAction methods have same-line braces. This is the preferred style of Xcode. This is how Xcode would have generated these methods automatically when you hooked them up.

Your other methods (and other constructs which require braces) have mostly used the new-line brace style.

It doesn't matter which you choose. What matters is consistency. And when you're writing in Xcode, the same-line brace style we see in your IBAction methods will be the easiest, because that's how Xcode will generate any methods automatically, and that's how Xcode will autocomplete methods from the superclass or protocols, and that's how Xcode will autocomplete things like for loops.

And in some cases, you've completely omitted braces, which you should never do.


You have inconsistent indentation.

By my count, things are indented by 0, 1, 2, 3, and 4 spaces, depending on where you look. You should pick one and stick to it. And make sure everything is indented the appropriate amount. Xcode will even completely do this for you. Start from the very top of your code, go to the first line that should be indented, backspace to the beginning of the line (Cmd+Backspace), and then push Tab once. Xcode knows exactly how far to indent it to get it to all line up.

There is a setting in Xcode that will let you specify how many spaces per indentation level.

Custom Navigation Bar View Implementation

The default setting is exactly as pictured here, and therefore, most all Xcode developers will have these settings. I recommend sticking with these settings unless you have a very compelling reason to use otherwise. And then, all that's left is to stop fighting Xcode and let it indent how it wants to.



Other notes...

Your IBOutlets and IBActions have no business in the header file. They're not open for public interaction (or shouldn't be) and as such, shouldn't be exposed to the public.

Your second comment here:

// Set left & right constraints to the container view

is in accurate. You have the same comment twice. One is above setting horizontal constraints, but the second is above setting vertical constraints.

Speaking of these constraints, it is exceptionally strange to waste time setting frames manually only to follow up by setting constraints. We really shouldn't be setting any constraints manually at all these days. Stick to setting up constraints properly. (And presumably, the 20 is to account for the status bar... but there's a way to constrain to this directly rather than hardcoding its height and hoping it doesn't change in iOS10+ [I don't know the way off the top of my head, but there's a way]).

There's no reason for the last method in your protocol (or any method) to start with a capital letter. It should be lower case. I know the Code Review syntax highlighting isn't perfect, but the fact that it did weird things for just that method should be a clue here.

If there is a means to set a property on an object, there should be a way to check that property. We don't expose a method to find out what the current title is set to.

We've not exploited Objective-C nullability annotations anywhere in our code. We should definitely be doing this, not only so that our code can be used from Swift without introducing implicitly unwrapped optionals (which are terrible), but also so that even in Objective-C, our code is more self-documenting. We have told users whether return values and arguments can be nil or should not be nil.

Related Articles

  • Custom Navigation Bar View Implementation

    Custom Navigation Bar View ImplementationJune 11

    In one of my app, i m using custom navigation bar view to handle all Navigation Bar Properties. Is it good practice to use custom navigation in given below way? Any Optimizations need to be done. It would be helpful to me, if you have any valuable su

  • Custom navigation bar via wp_list_pages is broken for blog rollSeptember 19

    Pretty simple question. I have the 'blog' on my site set via 'reading' to be the page 'blog' located at mysite.com/blog. /blog is hierarchical, in that it has children. I have a custom side bar that I include via a function in functions.php that does

  • Customizing navigation bar in beamer

    Customizing navigation bar in beamerMay 26

    I would like to customize the navigation bar (I'm using smoothbars) in beamer but I do not know how to proceed. To be more precise, I would like that all sections that appear on the navigation bar to be highlighted at the titlepage slide. This is the

  • Custom navigation bar in beamer?

    Custom navigation bar in beamer?October 2

    I need to get the navigation bar format in the diagram below on my frames. Any suggestions? \documentclass[svgnames]{beamer} \usetheme{Rochester} %\usetheme{CambridgeUS} \usepackage[british]{babel} \usepackage{tikz} \usetikzlibrary{positioning} %%%%%

  • How do I avoid hard coding the links in a custom made navigation bar?May 12

    I'm creating a custom navigation bar in drupal. I went ahead about this by creating it as a block and gave it all the neceassary CSS, but something that is not quit clear to me is how can I avoid the hard coding for the links? or any other ways that

  • Host-named Site Collections and Top Navigation barSeptember 13

    I have created a top navigation bar by implementing PortalSiteMapProvider and deploy it by a web scoped feature. if I create usual Site Collections Path-based SC it works and everything is ok, but if I create a Host-named site collection it generates

  • Click on navigation back button then navigation bar overlap same viewFebruary 1

    I have 3 View Controller A B and C. From B to C I can navigate portrait mode to Landscape mode. Now it is fine. When i am navigating from C to B (landscape to portrait mode) view controller. Then again now it is fine.But in C view controller i have o

  • react native - how to get form data when pressing on navigation bar submit button from a different view (class)February 12

    Hi I am new to React Native, so I might have missed on some tricks on how to do things properly. Sorry if the question in the title is a bit vague. Let me instead explain using an example: I have a file called root.js that navigates (using navigator)

  • Navigation Bar's Title View Overlaps

    Navigation Bar's Title View OverlapsFebruary 13

    I have added a custom titleView in Navigation Bar. In every screen change I am adding another title View. The problem is that the previous one is not get removed and I can See all Views at a time. Here is my code: UILabel *lblTitle = [[UILabel alloc]

  • Customizing iPhone app's navigation bar with custom typeface?

    Customizing iPhone app's navigation bar with custom typeface?July 9

    I'm currently designing my first iPhone application, and I've decided to go with a UI using the default UIKit controls, but customized with my own colors and textures. One area where I'm having trouble making a decision is whether or not to use a typ

  • Customizing Top navigation bar with javascriptApril 20

    I would like to make a customized the top navigation bar with mouse hoover and dropdown. The list is all sites that person have access too in that site collection. Since some people have access to quite a lot of sites, I hope I could achieve this wit

  • Conditional navigation bar on custom beamer theme

    Conditional navigation bar on custom beamer themeMarch 5

    I'm trying to create a custom beamer template. However, I can't make the navigation bar to correctly behave in the title page. As shown in the image, where the navigation bar is supposed to be I get a white bar instead of the navigation bar. How can

  • iOS: table view "Close", "Edit" and "+" button placement in a navigation barJuly 9

    There seems to exist some ambiguity when a table-based, multiple-item view needs to combine navigation ("Close"/"Back"), editing mode switching ("Edit") and aggregation ("+"/"Add") in a single navigation b

  • Customizing the navigation bar

    Customizing the navigation barJuly 12

    I was wondering how I can customize the sidebar such that it only shows the current section and subsections that I am currently presenting and how can I remove the navigation bar from the title slide. --------------Solutions------------- Hiding other

  • Enabling soft-keys navigation bar with custom ROM on Xolo A500SMarch 4

    I have Xolo A500S. I want to have navigation bars (soft-keys), but it does not work manually or by any app. Here is the build.prop. # begin build properties # autogenerated by buildinfo.sh ro.build.id=JDQ39 ro.build.display.id=Dark PureLolli By ACRD

  • How to display mutiple views on the 2013 SharePoint navigation bar for one Library

    How to display mutiple views on the 2013 SharePoint navigation bar for one LibraryJuly 23

    I want to use one SharePoint 2013 Library with multiple views and have links to each view on my navigation bar. I have created different views for the library but how do I lock those views in on my navigation bar? --------------Solutions-------------

  • How to correct the center of a view after extending it under navigation bar

    How to correct the center of a view after extending it under navigation barJanuary 23

    In this view controller, i have a navigation bar, an mkmapview, and a collection view. I have the following code: import UIKit import MapKit class PhotoAlbumViewController: UIViewController { var annotation: VTAnnotation! var span: MKCoordinateSpan!

  • Hiding Navigation bar short everything in view up

    Hiding Navigation bar short everything in view upJanuary 25

    I have the following storyboard setup: StoryBoard : I'm hiding the navigation and tool bars upon tap, however the UITextView shifts up when the navigation bars disappear. lyrics.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "show_

  • Load different views on angular directive through a navigation barFebruary 4

    I have a directive that loads three html files and I want to display that content inside my main view and switch beetwen this views across a nav bar but I dont know how to achive this. My directive: angular.module('headlinereport.Views', []) .directi

  • popToRootViewController brings last view over navigation bar

    popToRootViewController brings last view over navigation barFebruary 9

    I am running into a weird issue which when i use back functionality in my navigation hierarchy using [self.navigationController popViewControllerAnimated:YES]; it works fine and navigation is smooth but I am using popToRootViewController so as to per

Copyright (C) 2018 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.527 s.