2010-03-24 89 views
10

我正在UIToolbar上添加標籤(根據此技巧:Adding a UILabel to a UIToolbar)。我可以居中UIToolbar項目嗎?

但是,工具欄左側有一個按鈕,所以靈活的空間會將標籤從中心扔出,這正是我希望它的位置。我能以某種方式居中這個工具欄項目,以便它保持居中在工具欄中?

(已經嘗試過用虛擬固定空間平衡按鈕,沒有骰子。)

謝謝!

回答

3

最簡單的方法是將標籤放在以上,在它的父視圖中,並在此處證明它的正確性。

+0

感謝其他本,這是我的計劃B. :) –

+0

EricS的方法是優越的,更容易實現。 – titaniumdecoy

+1

當你改變方向時,EricS的方法是「靜態」,不起作用 – Undolog

35

在您的中心物品的左側和右側添加一個靈活的空間項目,就像您一樣。然後在最後添加一個固定的空間項目,並將寬度設置爲左側按鈕的寬度 - 大約是28個像素。

UIBarButtonItem *fixedItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL] autorelease]; 
fixedItem.width = 28; 
+7

這應該是被接受的答案。 – titaniumdecoy

+2

這假定系統字體永遠不會改變(它有好幾次),用戶永遠不會設置不同大小的字體。它也會忽略按鈕標題的本地化寬度。 –

6

要居中文本/標題工具欄上,你可以使用一個簡單的UILabel像見下圖:

UILabel *labelTitle = [[UILabel alloc] init]; 
labelTitle.font =[UIFont fontWithName:@"Helvetica-Bold" size:18]; 
labelTitle.backgroundColor = [UIColor clearColor]; 
labelTitle.textAlignment = UITextAlignmentCenter; 
labelTitle.userInteractionEnabled = NO; 
labelTitle.text = @"Your Title"; 
[labelTitle sizeToFit]; 
CGRect labelTitleFrame = labelTitle.frame; 
labelTitleFrame.size.width = self.toolbar.bounds.size.width; 
labelTitleFrame.origin.y = (self.toolbar.bounds.size.height - labelTitleFrame.size.height)/2; 
labelTitle.frame = labelTitleFrame; 
labelTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth; 
// Just add UILabel like UIToolBar's subview 
[self.toolbar addSubview:labelTitle]; 
[labelTitle release]; 
labelTitle = nil; 
+0

當您更改方向以及存在左側或右側條形按鈕時,此方法正常工作 – Undolog

0

是的,我們可以居中工具欄項目只是把兩種靈活的空間在工具欄像:

UIBarButtonItem *flexibaleSpaceBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 

toolbar.items = [NSArray arrayWithObjects:loginButton,flexibaleSpaceBarButton,toolBarLabel,flexibaleSpaceBarButton, nil]; 
相關問題