对齐 UIToolBar 项

我有三个 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];
66720 次浏览

将两个 UIBarButtonSystemItemFlexibleSpace 项添加到项的左侧和右侧的工具栏中

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

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

在 Xamarin iOS 中

右对齐:

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

Center Aligned:

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

这也可以通过故事板来完成。

Just drag and drop items in the toolbar, and turn some of them into flexible or fixed space to get the desired effect. See the two examples below.

Evenly spaced

Centered

Swift version:

    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]