UIToolbar - 添加相等宽度的按钮,没有间隙

时间:2018-04-26 15:54:22

标签: ios uibutton uitoolbar

我有UIToolbar,我想以相同的大小添加UIButtons。 目前,我有:

CGFloat width = self.toolbarMapMenu.frame.size.width / 4.0;
CGFloat height = self.toolbarMapMenu.frame.size.height;

btn0 = [self createMenuButton:@"a" width:width height:height];
btn1 = [self createMenuButton:@"b" width:width height:height];
btn2 = [self createMenuButton:@"c" width:width height:height];
btn3 = [self createMenuButton:@"d" width:width height:height];


UIBarButtonItem *it0 = [[UIBarButtonItem alloc] initWithCustomView:btn0];
UIBarButtonItem *it1 = [[UIBarButtonItem alloc] initWithCustomView:btn1];
UIBarButtonItem *it2 = [[UIBarButtonItem alloc] initWithCustomView:btn2];
UIBarButtonItem *it3 = [[UIBarButtonItem alloc] initWithCustomView:btn3];

[self.toolbarMapMenu setItems:[NSArray arrayWithObjects:
                               it0,  it1,  it2,  it3,
                               nil]
                            ];

和其他地方一样

-(UIButton *)createMenuButton: (NSString *)name width:(CGFloat) w height:(CGFloat) h
{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tintColor = [UIColor whiteColor];

    [btn setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];

    [[btn.widthAnchor constraintEqualToConstant: w] setActive:true];
    [[btn.heightAnchor constraintEqualToConstant: h] setActive:true];
    btn.translatesAutoresizingMaskIntoConstraints = false;

    return btn;
}

然而,当我添加这些按钮时,它们的大小相同,但是在firt / last按钮之前和之后有一个间隙:

Somethig喜欢这个(UIToolbar):

(<gap> btn0 btn1 btn2 btn3 <gap>)

如何删除此间隙并从toolbarMapMenu的开头有按钮?

1 个答案:

答案 0 :(得分:0)

尝试在每个项目之间添加灵活空间,它可以解决您的问题并提供一致的视图。

// Flexible Space
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

[self.toolbarMapMenu setItems:[NSArray arrayWithObjects:
                               it0, flexibleItem, 
                               it1, flexibleItem, 
                               it2, flexibleItem, 
                               it3,
                               nil]];