我可以将UIToolbar项目居中吗?

Ben*_*tto 12 iphone uitoolbar uibarbuttonitem uilabel

我在UIToolbar上放了一个标签(根据这个提示:将UILabel添加到UIToolbar).

但是工具栏的左侧有一个按钮,因此灵活的空间会将标签从中心抛出,这就是我想要的位置.我可以以某种方式居中这个工具栏项目,以便它保持在工具栏的中心?

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

谢谢!

Eri*_*icS 38

像您一样,在中心项目的左侧和右侧添加灵活的空间项目.然后在末尾添加一个固定的空格项,并将宽度设置为左按钮宽度的任何值 - 大约28像素.

UIBarButtonItem *fixedItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL] autorelease];
fixedItem.width = 28;
Run Code Online (Sandbox Code Playgroud)

  • 这假定系统字体永远不会改变(它有几次),用户永远不会设置不同大小的字体.它还忽略了按钮标题的不同宽度的本地化. (2认同)

Und*_*log 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;
Run Code Online (Sandbox Code Playgroud)


Ben*_*ieb 4

最简单的方法是将标签放在栏上方、其父视图中,并在那里对其进行调整。

  • EricS 的方法是“静态”的,当你改变方向时不起作用 (2认同)