我可以居中UIToolbar项目吗?

问题描述:

我正在UIToolbar上添加标签(根据此技巧:Adding a UILabel to a UIToolbar)。我可以居中UIToolbar项目吗?

但是,工具栏左侧有一个按钮,所以灵活的空间会将标签从中心扔出,这正是我希望它的位置。我能以某种方式居中这个工具栏项目,以便它保持居中在工具栏中?

(已经尝试过用虚拟固定空间平衡按钮,没有骰子。)

谢谢!

最简单的方法是将标签放在以上,在它的父视图中,并在此处证明它的正确性。

+0

感谢其他本,这是我的计划B. :) –

+0

EricS的方法是优越的,更容易实现。 – titaniumdecoy

+1

当你改变方向时,EricS的方法是“静态”,不起作用 – Undolog

在您的中心物品的左侧和右侧添加一个灵活的空间项目,就像您一样。然后在最后添加一个固定的空间项目,并将宽度设置为左侧按钮的宽度 - 大约是28个像素。

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

这应该是被接受的答案。 – titaniumdecoy

+2

这假定系统字体永远不会改变(它有好几次),用户永远不会设置不同大小的字体。它也会忽略按钮标题的本地化宽度。 –

要居中文本/标题工具栏上,你可以使用一个简单的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

是的,我们可以居中工具栏项目只是把两种灵活的空间在工具栏像:

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

toolbar.items = [NSArray arrayWithObjects:loginButton,flexibaleSpaceBarButton,toolBarLabel,flexibaleSpaceBarButton, nil];