I am trying to add a custom view in the center of a navigation bar and I am using the following code to test it:
UIView * testView = [[UIView alloc] init];
[testView setBackgroundColor:[UIColor blackColor]];
testView.frame = CGRectMake(0, 0, 100, 35);
[self.navigationController.navigationItem.titleView addSubview:testView];
I am setting this up in the viewDidLoad method of my view controller but when i run my program nothing seems to change in my navigation bar.
Could you help me with this?
If you want to just customize the title for one view controller you can use
or if you want to customize for all view controllers use
Replace
to
Edit:
Note: You cannot add subviews to titleView cause it's default value is
nil
, you need to set a new view as the titleView.Swift 3
One more alternate solution is
I recommend to use,
viewDidLoad
to setup yourtitleView
You'll want to use storyboard to do this to support iPhone 6 and newer (larger) devices.
Create a container view for your custom navigation item title/subtitle etc, and drag it into the visual editor (not into the view hierarchy).