均匀地水平分布三个按钮

时间:2017-06-03 13:33:08

标签: ios objective-c uiview uibutton frame

我有三个UIButtons和一个持有人UIView我希望我的三个UIButtonUIView内垂直居中,我希望它们水平分布

float ycentre = CGRectGetMidY(self.buttonHolderView.bounds);
float xposition = (self.buttonHolderView.frame.size.width - 135.0f)/4.0f;


self.button1 = [[UIButton alloc]initWithFrame:CGRectMake(xposition,0, 45, 30)];
self.button1.center = CGPointMake(self.button1.frame.origin.x, ycentre);


self.button2 = [[UIButton alloc]initWithFrame:CGRectMake((xposition*2)+45,0, 45, 30)];
self.button2.center = CGPointMake(self.button2.frame.origin.x, ycentre);

self.button3 = [[UIButton alloc]initWithFrame:CGRectMake((xposition*3)+90,0, 45, 30)];
self.button3.center = CGPointMake(self.button3.frame.origin.x, ycentre);
[self.button3 addTarget:self action:@selector(ShareButtonClicked) forControlEvents:UIControlEventTouchUpInside];

[self.buttonHolderView addSubview:self.button1];
[self.buttonHolderView addSubview:self.button2];
[self.buttonHolderView addSubview:self.button3];

每个按钮的高度为30,宽度为45,但是我的代码并没有将它们分配给出错的地方?

3 个答案:

答案 0 :(得分:2)

将它们放在UIStackView中。它使间距视图非常容易。

答案 1 :(得分:0)

按如下方式设置按钮的frame,不要设置center

float thirdOfWidth = (self.buttonHolderView.frame.width/3.0);
float buttonWidth = 45.0;
float buttonHeight = 30.0;

self.button1 = [[UIButton alloc]initWithFrame:CGRectMake(thirdOfWidth*0 + (thirdOfWidth - buttonWidth)/2, (self.buttonHolderView.frame.height - buttonHeight)/2, 45, 30)];

self.button2 = [[UIButton alloc]initWithFrame:CGRectMake(thirdOfWidth*1 + (thirdOfWidth - buttonWidth)/2, (self.buttonHolderView.frame.height - buttonHeight)/2, 45, 30)];

self.button3 = [[UIButton alloc]initWithFrame:CGRectMake(thirdOfWidth*2 + (thirdOfWidth - buttonWidth)/2, (self.buttonHolderView.frame.height - buttonHeight)/2, 45, 30)];

答案 2 :(得分:0)

也可以循环使用任意数量的按钮

        NSInteger count = 3;
        CGFloat buttonWidth = 45;
        CGFloat buttonHeight = 30;
        CGFloat x = (self.bounds.size.width - buttonWidth) / 2;
        CGFloat verticalSpacing = ((self.bounds.size.height - buttonHeight * count) / count) - buttonHeight / 2;
        CGFloat y = verticalSpacing;

        for (int i = 0; i < count; i++) {
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, y, buttonWidth, buttonHeight)];
            [self addSubview:button];
            y += buttonHeight + verticalSpacing;
        }