1

在我UINavigationBar我有一個多行標題,我使用的代碼設置如下:定心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;我的標題將居中,但它實際上是從我的「返回」按鈕的末尾到我的屏幕末尾將我的標題居中。

我該如何重寫這個,以便我的標題實際上是基於我的屏幕尺寸居中的(基本上,如果後退按鈕不存在,它的默認方式)。

回答

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移動的寬度。

+0

這工作完美!取得了我想要的結果,謝謝! – vzm