简体   繁体   English

在视图控制器宽度上水平均匀分布UIButton的最简单方法是什么?

[英]Simplest way to evenly distribute UIButtons horizontally across width of view controller?

I've looked through many answers and they all seem very complex! 我看了很多答案,看起来都很复杂! Most recently I was looking at this answer although I'd prefer not to have to put my buttons inside views. 最近我看到了这个答案,虽然我不想把我的按钮放在视图中。

I have 6 UIButtons that are all the same dimensions. 我有6个UIButton,它们都是相同的尺寸。 I want to space them evenly horizontally across the full width and at the bottom of my root view controller. 我想将它们均匀地水平分布在我的根视图控制器的整个宽度和底部。

|                                      |
|                                      |
|  [b1]  [b2]  [b3]  [b4]  [b5]  [b6]  |
________________________________________

What is the simplest way to achieve this programmatically? 以编程方式实现此目的的最简单方法是什么?

I think this is simpler than the link on the accepted answer. 我认为这比接受答案的链接更简单。 Ok, firstly lets create some buttons: 好的,首先让我们创建一些按钮:

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
button1.translatesAutoresizingMaskIntoConstraints = NO;
[button1 setTitle:@"Btn1" forState:UIControlStateNormal];

... do that 6 times for 6 buttons, however you like then add them to the view: ...为6个按钮做6次,但是你喜欢然后将它们添加到视图中:

[self.view addSubview:button1];
[self.view addSubview:button2];
[self.view addSubview:button3];
[self.view addSubview:button4];
[self.view addSubview:button5];
[self.view addSubview:button6];

Fix one button to the bottom of your view: 将一个按钮修复到视图的底部:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:button1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];

Then tell all the buttons to be equal width and spread out equally across the width: 然后告诉所有按钮宽度相等,并在宽度上均匀分布:

NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2, button3, button4, button5, button6);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[button1][button2(==button1)][button3(==button1)][button4(==button1)][button5(==button1)][button6(==button1)]|" options:NSLayoutFormatAlignAllBottom metrics:nil views:views]];

Result: 结果:

在此输入图像描述

I know this question is a bit old, but I've been programming in iOS for a few years now and dislike using autolayout. 我知道这个问题有点老了,但我已经在iOS上编程了几年了,不喜欢使用autolayout。 So I wrote a helper method to evenly space UIButtons horizontally and center them vertically within a UIView. 所以我编写了一个辅助方法来水平均匀地分隔UIButtons并将它们垂直居中在UIView中。 This works great for menu bars. 这适用于菜单栏。

- (void) evenlySpaceTheseButtonsInThisView : (NSArray *) buttonArray : (UIView *) thisView {
    int widthOfAllButtons = 0;
    for (int i = 0; i < buttonArray.count; i++) {
        UIButton *thisButton = [buttonArray objectAtIndex:i];
        [thisButton setCenter:CGPointMake(0, thisView.frame.size.height / 2.0)];
        widthOfAllButtons = widthOfAllButtons + thisButton.frame.size.width;
    }

    int spaceBetweenButtons = (thisView.frame.size.width - widthOfAllButtons) / (buttonArray.count + 1);

    UIButton *lastButton = nil;
    for (int i = 0; i < buttonArray.count; i++) {
        UIButton *thisButton = [buttonArray objectAtIndex:i];
        if (lastButton == nil) {
            [thisButton setFrame:CGRectMake(spaceBetweenButtons, thisButton.frame.origin.y, thisButton.frame.size.width, thisButton.frame.size.height)];
        } else {
            [thisButton setFrame:CGRectMake(spaceBetweenButtons + lastButton.frame.origin.x + lastButton.frame.size.width, thisButton.frame.origin.y, thisButton.frame.size.width, thisButton.frame.size.height)];
        }

        lastButton = thisButton;
    }
}

Just copy and paste this method into any view controller. 只需将此方法复制并粘贴到任何视图控制器中。 Then to access it, I first created all the buttons I wanted, then called the method with all of the buttons in an array, along with the UIView I wanted it in. 然后,为了访问它,我首先创建了我想要的所有按钮,然后使用数组中的所有按钮调用方法,以及我想要的UIView。

[self evenlySpaceTheseButtonsInThisView:@[menuButton, hierarchyMenuButton, downButton, upButton] :menuView];

The advantage of this method is that you don't need autolayout and it's super easy to implement. 这种方法的优点是您不需要自动布局,并且它非常容易实现。 The disadvantage is that if your app works in landscape and portrait, you will need to make sure to call this method again after the view has been rotated. 缺点是,如果您的应用程序在横向和纵向中工作,则需要确保在旋转视图后再次调用此方法。

I usually do something like: 我经常这样做:

int numButtons = 6;
float gap = 10.0f;
float y = 50.0f;
float width = (self.view.frame.size.width - gap * (numButtons + 1)) / numButtons;
float height = 60.0f;
for (int n=0;n<numButtons;n++) {
    float x = gap * (n+1) + width * n;
    UIButton *button = [self.buttons objectAtIndex:n]; //Or get button some other way/make button.
    [button setFrame:CGRectMake(x,y,width,height)];
}

You can set numButtons to however many buttons you want in the row, and if you have an array of buttons, you can set it to the length of that array. 您可以将numButtons设置为行中所需的多个按钮,如果您有一个按钮数组,则可以将其设置为该数组的length

The y is just whatever y coordinate you want and the same goes for the height and gap, which is the space between buttons. y就是你想要的任何y坐标,高度和间隙也是如此,这是按钮之间的空间。 The width is just a calculation of how wide each button will be based on the screen width and the gap space you want between each button. 宽度只是根据屏幕宽度和每个按钮之间所需的间隙空间计算每个按钮的宽度。

You can send the Label/button/view's as array to this methods and arrange the button frames. 您可以将标签/按钮/视图作为数组发送到此方法并排列按钮帧。

-(void)arrangeViewsXposition:(NSArray*)anyView y:(CGFloat)y width:(CGFloat)width height:(CGFloat)height mainViewWdith:(UIView*)mainview {
int count = (int)anyView.count;
CGFloat widthTemp = mainview.bounds.size.width, temp1 = widthTemp-(width*count),space = temp1/(count+1);
for (int i = 0; i<count; i++) {
    UIView *btnTemp = (UIView*)[anyView objectAtIndex:i];
    if (btnTemp) {
        btnTemp.frame = CGRectMake(space+((space+width)*i), y, width, height);
    }
}
}

Call this method like this: 像这样调用这个方法:

[self arrangeViewsXposition:@[btnSave,btnCancel] y:5 width:80 height:30 mainViewWdith:footerView];

There are a number of decent auto-layout solutions discussed in this question: 在这个问题中讨论了许多不错的自动布局解决方案:

Evenly space multiple views within a container view 在容器视图中均匀分隔多个视图

Basically it can be a lot of manual constraint-definition code, which can be conveniently wrapped in a category extension for encapsulation/reuse. 基本上它可以是很多手动约束定义代码,可以方便地包装在类别扩展中以进行封装/重用。

I just cooked this up in Swift using Cartography . 我刚刚使用制图在Swift中制作了这个。

func disributeEvenlyAcrossWithCartography(views: [UIView], enclosingBox: UIView, spacer: CGFloat = 10.0) {
    var priorView = UIView() // never null
    for (index, view) in views.enumerate() {
        constrain(view, priorView, enclosingBox) { view, prior, enclosingBox in
            view.height == enclosingBox.height
            view.centerY == enclosingBox.centerY
            if index == 0 {
                view.width == enclosingBox.width / CGFloat(views.count) - spacer
                view.left == enclosingBox.left
            } else {
                view.left == prior.right + (spacer + spacer / CGFloat(views.count - 1))
                view.width == prior.width
            }
        }
        priorView = view
    }
}

Result with 5 views and a small spacer: 结果有5个视图和一个小间隔:

在此输入图像描述

This is my first post on Stackoverflow. 这是我在Stackoverflow上的第一篇文章。 This site has been very helpful in getting me up to speed on Xcode and swift. 这个网站非常有助于我快速掌握Xcode和swift。 Anyway, below is my quick-and-dirty fix to the above question. 无论如何,下面是我对上述问题的快速修复。

Pin the left most button and the right most button, respectively. 分别固定最左侧按钮和最右侧按钮。 Create "dummy" labels between each of the buttons. 在每个按钮之间创建“虚拟”标签。 Set all of the "dummy" labels as equal widths. 将所有“虚拟”标签设置为相等的宽度。 For each of the "dummy" label, add constraints (0 to the nearest neighbor on the left, and 0 to the nearest neighbor on the right). 对于每个“虚拟”标签,添加约束(0到左边最近的邻居,0到右边最近的邻居)。 The buttons will then be equally spaced throughout, even when you change from portrait to landscape orientation. 即使您从纵向更改为横向,按钮也会在整个过程中保持相等的间距。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM