如何在iOS通用应用程序中对齐UIToolbar中的UIBarButtonItem?

25
我想在我的iOS通用应用程序中将两个UIBarButtonItem实例放到UIToolbar中,其中第一个项目位于工具栏的左边缘,第二个项目位于中心。然而,看起来这不能在Interface Builder中完成,因为自动布局不支持强制约束UIBarButtonItem类,因为它不是从UIView子类派生的。 请注意,我不想把第一个按钮放在左侧边缘,第二个按钮放在右侧边缘 - 我必须把第二个按钮放在中心。而且,我没有计划使用第三个按钮以便将它们对齐为左、中、右等间隔。
在Storyboard中,是否仍然可以在此情况下添加这样的约束?我使用的是Xcode 6 beta 5。
4个回答

78

你可以在Storyboard中完成所有操作。

在对象库中选择一个Bar Button Item,将它拖到你的Toolbar中。在它的右边添加一个Flexible Space Bar Button Item,再在它的右边添加第二个Bar Button Item。然后,在它的右边再添加一个Flexible Space Bar Button Item

在Interface Builder中,结果看起来像这样:

enter image description here

如果需要,你可以在你的Toolbar的右边缘添加一个额外的Fixed Space Bar Button Item,以确保你的第二个Bar Button Item 真正居中。

用户lxt在回答类似问题的另一篇答案这里给出了另一个例子。

编辑:请确保您的UIToolbar具有良好的约束条件,然后再进行操作!


你试过运行模拟器吗?实际上,在发布这个问题之前,我已经尝试过了,但它会在左右边缘放置两个栏按钮。 - Blaszard
我再试了一次,但还是不行。你选择了通用应用程序模板吗? - Blaszard
这个答案对我也有用。我本来想建议在右边缘添加一个零宽度的固定空格,但是它并没有任何区别,因为弹性空间会增长到最大可能值(答案也建议了这一点,呃!)。@Gardecolo,你能否发布你当前不工作的视图层次结构的屏幕截图(IB的左侧部分)? - Warren Burton
谢谢,沃伦。我明白了为什么它不能在我的应用程序中工作,因为我没有添加工具栏水平边缘的约束条件,而且由于“实际中心位置”显示在“4英寸iPhone的右侧边缘”,我没有意识到这是问题的起源。添加-16水平约束可以使其在iPhone和iPad上正常工作。 - Blaszard
你说得对:我在帖子中没有提到我在将工具栏添加到我的视图控制器场景后立即添加了自动布局约束。实际上,这是问题的一部分... - Imanou Petit

5
您可以通过编程来实现这一点。
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"item1" style:UIBarButtonItemStylePlain target:self action:nil];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithTitle:@"item2" style:UIBarButtonItemStylePlain target:self action:nil];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"item3" style:UIBarButtonItemStylePlain target:self action:nil];

self.toolbarItems = [NSArray arrayWithObjects: item1, flexible, item2, flexible, item3, nil];

如果您想了解更多详情,请查看此链接

如何将UIBarButtonItem放置在UIToolbar的右侧?


由于某种原因,当我添加*flexible时,它只是将所有的BarButtonItems叠放在一起。 - Trip

3

2

添加工具栏的代码:

这里,固定宽度可以是可变的。因此,您可以将其保持在所需位置,以使第二个按钮居中。

UIBarButtonItem *fixedItemSpaceWidth = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

    fixedItemSpaceWidth.width = 200.0f; // or whatever you want

    UIBarButtonItem *doneBarButton  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonAction:)];

            UIBarButtonItem *cancelBarButton  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonAction:)];

            // Initialise toolabr
            UIToolbar *toolbar          = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-44, 320, 44)];
            //toolbar.barStyle = UIBarStyleBlack;
            toolbar.items               = [NSArray arrayWithObjects:cancelBarButton,fixedItemSpaceWidth,doneBarButton, nil];
        [self.view addSubview:toolbar];

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