集中UINavigationBar标题文本问题

时间:2013-08-01 20:47:45

标签: ios objective-c uinavigationcontroller uinavigationbar uinavigationitem

在我的UINavigationBar我有一个多行标题,我使用以下代码进行设置:

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;

由于这是在子视图上,因此它有一个“后退”按钮,由UINavigationController添加。所以我想通过添加label.textAlignment = NSTextAlignmentCenter;我的标题会居中,但它实际上是将我的标题从我的“后退”按钮的末尾到屏幕的末尾。

如何覆盖这个,以便我的标题实际上是根据我的屏幕尺寸居中的(基本上,如果后面的按钮不存在,它的默认方式)。

1 个答案:

答案 0 :(得分:2)

这个问题非常艰难。如果我找到一个更优雅的解决方案,我会编辑我的答案,但这就是我想出的:

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

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

只需调整UIView的宽度,以确定titleLabel的移动距离。