115

UIBarButtonItem创建了三个如下。它们向左对齐,我想对齐中心,所以右侧没有间隙。我没有看到 align 属性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

4 回答 4

262

将两个 UIBarButtonSystemItemFlexibleSpace 项目添加到您的工具栏,在项目的左侧和右侧

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

像添加任何其他工具栏项一样添加这些项将在它们两者之间平均分配空间。

于 2009-03-02T15:42:29.037 回答
31

这也可以直接从情节提要中完成。

只需在工具栏中拖放项目,将其中一些变成灵活或固定的空间即可获得所需的效果。请参阅下面的两个示例。

均匀分布的

居中

于 2014-11-28T14:55:47.583 回答
9

在 Xamarin iOS 中

右对齐:

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

居中对齐:

var flexibleSpace = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
yourBar.SetItems(new [] { flexibleSpace, yourButton, flexibleSpace}, false);
于 2013-01-24T07:10:45.790 回答
9

斯威夫特版本:

    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]
于 2016-05-06T05:43:24.487 回答