ios - 居中 UINavigationBar 标题文本问题

标签 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;

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

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

最佳答案

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

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

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

只需根据您希望 titleLabel 移动的距离调整 UIView 的宽度。

关于ios - 居中 UINavigationBar 标题文本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004242/

相关文章:

iphone - 从基于窗口的项目开始构建基于导航的项目

iphone - 在 ios 中将字符串中的两个值加在一起

iOS//显示html -> 富文本

objective-c - 在 C 中使用 char,指针问题, Objective-C

iphone - 更改 UINavigationBar 的后退按钮

ios - 以编程方式创建和显示 UIBarButtonItem 的正确方法是什么?

objective-c - 如何将数据从 uitableview 传递到 Storyboard中的详细 View

ios - 如何在播放 youtube 视频时访问 ios 媒体播放器实例

ios - 将数据从 TableView Controller 传递到选项卡 View 中包含的另一个 View Controller ?

ios - 获取 UITableView 中最后一行的索引路径