2014-02-21 52 views
0

我有以下一個導航欄:間距導航欄按鈕,這樣一個按鈕旁邊的標題

左:用背單詞箭頭「回」一路向左

右:2巴按鈕一路向右

中心:標題文本

我想第三個按鈕添加到對按鈕的右側(這些按鈕的左側),但我希望這是之間的空間這個新按鈕和其他按鈕,使這個新按鈕擁抱在標題的右側。我嘗試使用FixedSpace BarButtonItem。這是我到目前爲止:

UIBarButtonItem* space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil]; 
space.width = 160; 
UIBarButtonItem* thirdButton = [[UIBarButtonItem alloc] initWithImage:myImage style:UIBarButtonItemStylePlain target:self action:@selector(action)]; 

NSMutableArray* buttons = [self.navigationItem.rightBarButtonItems mutableCopy];  
//index 0 & 1 are the buttons that are already there 
[buttons setObject:space atIndexedSubscript:2]; 
[buttons setObject:button atIndexedSubscript:3]; 
[self.navigationItem setRightBarButtonItems:buttons]; 

這樣做確實會在第三個按鈕和其他按鈕之間創建一個空格。問題在於,標題可以是動態的,並且由於這個固定的空間,它並不總是居中。在右側添加固定空間會導致標題向左移動,看起來很奇怪,具體取決於標題大小。我需要一種方法來確定標題的位置以及它的時間。有沒有辦法做到這一點?像navBar.title.widthnavBar.title.origin之類的東西,這樣我可以計算出從導航欄的最右邊到標題有多少點?

+0

將'titleView'設置爲標題和所需按鈕標籤的自定義視圖可能會更好。 – rmaddy

回答

0

要計算導航欄中標題的大小,您只需遵循以下步驟。

NSDictionary *attributes = [self.navigationController.navigationBar titleTextAttributes]; 
CGSize titleSize = [self.title sizeWithAttributes:attributes]; 

現在您可以使用標題的大小和按鈕的大小來計算固定空間的寬度。

+0

非常好!正是我需要的,謝謝! – Hash88