I am using a custom title view for a UINavigationBar with the following code:
// Set a label to the nav bar
THLabel *titleLabel = [[THLabel alloc] init];
titleLabel.text = @"Test";
titleLabel.font = [UIFont fontWithName:APP_FONT size:22.0];
titleLabel.frame = CGRectMake(0, 0, 100, 30);
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.textColor = CUSTOM_LIGHT_BLUE;
titleLabel.strokeColor = kStrokeColor;
titleLabel.strokeSize = kStrokeSize;
self.navigationItem.titleView = titleLabel;
The problem is that when presenting a new viewcontroller and then returning to the original view controller this custom view shifts and then re-centers itself. Please see the video for a demonstration of that.
Please see the video here: https://www.youtube.com/watch?v=961CCVQmpJM&feature=youtu.be
I have disabled autoresizing of every subview for the navigation controller with both the storyboard and in code for each view controller:
// Set the navigation bar hidded on the log in view
UINavigationController* mainViewController = (UINavigationController*)self.appDelegate.window.rootViewController;
[mainViewController setNavigationBarHidden:YES];
[[mainViewController navigationBar] setAutoresizesSubviews:NO];
However it still resizes! How can I stop this - what am I doing wrong? Thanks!
Expanding on @Alex Peda's answer above, I'm finding that on iOS7, outside of viewDidLoad, there appears to be a minimum title width for a custom title. Here's what I'm doing, below. Note there are a few methods below particular to my code.
I would embed the label inside a
UIView
. Interface Builder doesn't like putting directly aUILabel
in thetitleView
for some reason that may be related to your problem.Also try to set the
autoResizingMask
toUIViewAutoresizingFlexibleTopMargin
. In my experience any custom view in bars behaves better this way.What worked for me was to create a variable in the view controller that holds your desired title view then initialize it in
viewDidLoad
. Then you can set that view to theself.navigationItem.titleView
inviewWillAppear
and it should display properly. No need for setting autoResizeMask, or rightBarButtons, etc.Example:
This happened for me as well. Two things you could do :
1) make sure navigation setup is done in either viewDidLayoutSubviews or viewDidLoad as mentioned in the above answer
2) i had left and right bar button item as nil, but only called them after the title label was set. make sure to set the right and left bar button items as nil (if you are not using them of course) before setting the titlelabel to titleview.
It's reproducible for me only if I place setting titleView code in viewWillAppear. Moving it to viewDidLoad fixes the issue
In my case it happened because I was setting UIBarButton before titleView. Setting titleView should be first. Works perfectly now.