简体   繁体   中英

Centering UINavigationBar title text issue

In my UINavigationBar I have a multi line title, I am using the following the code to setup:

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 480, 50)];
label.backgroundColor = [UIColor clearColor];
label.numberOfLines = 2;
label.font = [UIFont boldSystemFontOfSize: 15.0f];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = @"Headloss due to Friction              (Hazen Williams Eq.)";

self.navigationItem.titleView = label;

Since this is on a sub-view it has a "Back" button, added by the UINavigationController . So I figured that by adding the label.textAlignment = NSTextAlignmentCenter; my title would be centered, but it's actually centering my title from the end of my "Back" button to the end of my screen.

How can I override this so that my title is actually centered based on my screen dimension, (basically, the way it would be by default should the back button not be present).

Good question that's pretty tough. If I find a more elegant solution I'll edit my answer but this is what I came up with:

UIView *spaceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];

UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithCustomView:spaceView];
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObject:space];

And just adjust the width of the UIView for how far you want your titleLabel to move.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM