UIToolBar项目的对齐方式

117

我有三个UIBarButtonItem,如下所示。它们靠左对齐,我想将它们居中对齐,以便右侧没有间隙。 我在UIToolBar上看不到对齐属性。 有没有其他方法可以实现这一点?

//create some buttons
UIBarButtonItem *aboutButton = [[UIBarButtonItem alloc] initWithTitle:@"About" style:UIBarButtonItemStyleBordered target:self action:@selector(showAbout:)];
[toolbar setItems:[NSArray arrayWithObjects:settingsButton,deleteButton,aboutButton,nil]];
//Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];
4个回答

263

将两个UIBarButtonSystemItemFlexibleSpace项目添加到工具栏中,分别位于您的项目左侧和右侧。

UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, settingsButton,deleteButton,aboutButton, flexibleSpace, nil]];

将它们像其他工具栏项一样添加,这将在它们之间均匀分配空间。


25
没有实际的理由去创建多个可伸缩空间。如果需要更多的话,您可以将同一多个可伸缩空间对象多次添加到工具栏中。 - mmc
mmc是正确的。事实上,将一个单例flexibleSpace并在整个产品中重复使用它可能是完全合理的。我听说过有人声称这是单例的真正原始用途:不是为了强制执行程序规则,而是为了减少开销。 - Amagrammer
2
你忘记更新释放调用了,应该写成[flexibleSpace release]; - Daniel Hepper
是的,抱歉,它读取的是 [flexibleSpaceLeft release] 而不是 [flexibleSpace release]。笔误已经修正了。 - nduplessis

32

这也可以直接从故事板中完成。

只需在工具栏中拖放项目,并将其中一些项目转换为可伸缩或固定空间,即可获得所需的效果。请参见下面的两个示例。

等距离间隔

居中对齐


9

Swift版本:

    let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: viewController.view.frame.size.width, height: 35.0))
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: viewController, action: nil)
    let button1 = UIBarButtonItem(title: "A", style: UIBarButtonItem.Style.Plain, target: viewController, action: foo)
    let button2 = UIBarButtonItem(title: "B", style: UIBarButtonItem.Style.Plain, target: viewController, action: bar)
    let button3 = UIBarButtonItem(title: "C", style: UIBarButtonItem.Style.Plain, target: viewController, action: blah)
    toolbar.items = [button1, flexibleSpace, button2, flexibleSpace, button3]

9
在 Xamarin iOS 中,右对齐:

Right aligned:

yourBar.SetItems(new [] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), yourButton }, false);

居中对齐:

var flexibleSpace = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
yourBar.SetItems(new [] { flexibleSpace, yourButton, flexibleSpace}, false);

7
这不是我们讨论的话题,我们在这里只谈纯iOS相关的内容。 - jturolla
4
这是MonoTouch的目标对象。 - Herman Schoenfeld
2
Objective C问题,不是MonoTouch/C#。 - Max MacLeod
6
@MaxMacLeod: 它没有被标记为obj-c,而是被标记为iPhone。因此我的答案是有效的。对比C#和Obj-C也是一个好主意。很明显,C#是现代、更轻巧、更漂亮、更快速和更优越的。 - Herman Schoenfeld
14
虽然问题中的代码明显是Objective-C,但我发现这个答案很有用。它在Google中排名很高。 - jacob.toye
虽然不是对主要问题的好答案,但对我在使用Xamarin方面很有帮助。谢谢! - bdrelling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接