自动布局让我的生活很困难。从理论上讲,当我转换的时候,它会非常有用,但我似乎一直在与它作斗争。

我做了一个演示项目来寻求帮助。有人知道如何使视图之间的空间增加或减少均匀,每当视图调整大小?

下面是三个标签(手动垂直对齐):

我想要的是,当我旋转时,它们均匀地调整间距(而不是视图大小)。默认情况下,顶部和底部视图向中心挤压:


当前回答

查看https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutbyExample/AutoLayoutbyExample.html,上面有关于解决问题的详细描述。

其他回答

我刚刚用乘数特性解决了我的问题。我不确定它是否适用于所有情况,但对我来说,它非常有效。我在Xcode 6.3供你参考。

我最后做的是:

1)首先将我的按钮放置在320px宽度的屏幕上,以我希望它在320px设备上的方式分布。

2)然后我在所有按钮的superview上添加了一个领先的空间约束。

3)然后我修改了前导空间的属性,使常量为0,乘数是x偏移量除以屏幕宽度(例如,我的第一个按钮距离左边缘8px,所以我将乘数设置为8/320)

4)那么这里重要的一步是将约束关系中的第二个Item更改为superview。尾随而不是superview.leading。这很关键,因为superview。在我的例子中,前导为0,后拖为320,所以8/320在320px设备上是8px,然后当父视图的宽度改变为640或其他什么时,视图都以相对于320px屏幕大小的宽度的比例移动。这里的数学比较容易理解。

Android has a method of chaining views together in its constraint based layout system that I wanted to mimic. Searches brought me here but none of the answers quite worked. I didn't want to use StackViews because they tend to cause me more grief down the line than they save up front. I ended up creating a solution that used UILayoutGuides placed between the views. Controlling their width's allows different types of distributions, chain styles in Android parlance. The function accepts a leading and trailing anchor instead of a parent view. This allows the chain to be placed between two arbitrary views rather than distributed inside of the parent view. It does use UILayoutGuide which is only available in iOS 9+ but that shouldn't be a problem anymore.

public enum LayoutConstraintChainStyle {
    case spread //Evenly distribute between the anchors
    case spreadInside //Pin the first & last views to the sides and then evenly distribute
    case packed //The views have a set space but are centered between the anchors.
}

public extension NSLayoutConstraint {

    static func chainHorizontally(views: [UIView],
                                  leadingAnchor: NSLayoutXAxisAnchor,
                                  trailingAnchor: NSLayoutXAxisAnchor,
                                  spacing: CGFloat = 0.0,
                                  style: LayoutConstraintChainStyle = .spread) -> [NSLayoutConstraint] {
    var constraints = [NSLayoutConstraint]()
    guard views.count > 1 else { return constraints }
    guard let first = views.first, let last = views.last, let superview = first.superview else { return constraints }

    //Setup the chain of views
    var distributionGuides = [UILayoutGuide]()
    var previous = first
    let firstGuide = UILayoutGuide()
    superview.addLayoutGuide(firstGuide)
    distributionGuides.append(firstGuide)
    firstGuide.identifier = "ChainDistribution\(distributionGuides.count)"
    constraints.append(firstGuide.leadingAnchor.constraint(equalTo: leadingAnchor))
    constraints.append(first.leadingAnchor.constraint(equalTo: firstGuide.trailingAnchor, constant: spacing))
    views.dropFirst().forEach { view in
        let g = UILayoutGuide()
        superview.addLayoutGuide(g)
        distributionGuides.append(g)
        g.identifier = "ChainDistribution\(distributionGuides.count)"
        constraints.append(contentsOf: [
            g.leadingAnchor.constraint(equalTo: previous.trailingAnchor),
            view.leadingAnchor.constraint(equalTo: g.trailingAnchor)
        ])
        previous = view
    }
    let lastGuide = UILayoutGuide()
    superview.addLayoutGuide(lastGuide)
    constraints.append(contentsOf: [lastGuide.leadingAnchor.constraint(equalTo: last.trailingAnchor),
                                    lastGuide.trailingAnchor.constraint(equalTo: trailingAnchor)])
    distributionGuides.append(lastGuide)

    //Space the according to the style.
    switch style {
    case .packed:
        if let first = distributionGuides.first, let last = distributionGuides.last {
            constraints.append(first.widthAnchor.constraint(greaterThanOrEqualToConstant: spacing))
            constraints.append(last.widthAnchor.constraint(greaterThanOrEqualToConstant: spacing))
            constraints.append(last.widthAnchor.constraint(equalTo: first.widthAnchor))
            constraints.append(contentsOf:
                distributionGuides.dropFirst().dropLast()
                    .map { $0.widthAnchor.constraint(equalToConstant: spacing) }
                )
        }
    case .spread:
        if let first = distributionGuides.first {
            constraints.append(contentsOf:
                distributionGuides.dropFirst().map { $0.widthAnchor.constraint(equalTo: first.widthAnchor) })
        }
    case .spreadInside:
        if let first = distributionGuides.first, let last = distributionGuides.last {
            constraints.append(first.widthAnchor.constraint(equalToConstant: spacing))
            constraints.append(last.widthAnchor.constraint(equalToConstant: spacing))
            let innerGuides = distributionGuides.dropFirst().dropLast()
            if let key = innerGuides.first {
                constraints.append(contentsOf:
                    innerGuides.dropFirst().map { $0.widthAnchor.constraint(equalTo: key.widthAnchor) }
                )
            }
        }
    }

    return constraints
}

查看开源库PureLayout。它提供了一些用于分布视图的API方法,包括每个视图之间的间距是固定的(视图大小根据需要而变化),以及每个视图的大小是固定的(视图之间的间距根据需要而变化)。请注意,所有这些都是在没有使用任何“间隔视图”的情况下完成的。

从NSArray + PureLayout.h:

// NSArray+PureLayout.h

// ...

/** Distributes the views in this array equally along the selected axis in their superview. Views will be the same size (variable) in the dimension along the axis and will have spacing (fixed) between them. */
- (NSArray *)autoDistributeViewsAlongAxis:(ALAxis)axis
                                alignedTo:(ALAttribute)alignment
                         withFixedSpacing:(CGFloat)spacing;

/** Distributes the views in this array equally along the selected axis in their superview. Views will be the same size (fixed) in the dimension along the axis and will have spacing (variable) between them. */
- (NSArray *)autoDistributeViewsAlongAxis:(ALAxis)axis
                                alignedTo:(ALAttribute)alignment
                            withFixedSize:(CGFloat)size;

// ...

由于它都是开源的,如果您有兴趣了解如何在没有间隔视图的情况下实现这一点,只需查看实现即可。(这取决于同时利用约束的常数和乘数。)

我也有类似的问题,发现了这篇文章。但是,目前提供的答案中没有一个能以您想要的方式解决问题。他们没有使间距相等,而是平均分配标签的中心。重要的是要明白这是不一样的。我画了一个小图来说明这一点。

有3个视图,都是20点高。使用任何建议的方法都可以均匀地分布视图的中心,并为您提供插图布局。注意,视图的y中心间隔相等。但是,父视图和顶视图之间的间距是15pt,而子视图之间的间距只有5pt。为了使视图间距相等,这两个视图的间距都应该是10pt,即所有蓝色箭头的间距都应该是10pt。

然而,我还没有想出一个好的通用解决方案。目前我最好的想法是插入“间距视图”之间的子视图和设置间距视图的高度相等。

看,没有间隔!

根据我最初回答的评论部分的建议,特别是@Rivera的有用建议,我简化了我的原始答案。

我用动图来说明这有多简单。我希望这些动图对你有帮助。为了防止你对动图有问题,我在下面附上了旧的答案和简单的屏幕截图。

产品说明:

1)添加按钮或标签。我用了3个按钮。

2)从每个按钮添加一个中心x约束到superview:

3)从每个按钮添加一个约束到底部布局约束:

4)调整上文第3条添加的约束如下:

A)选择约束; B)去掉常数(设为0), c)更改乘数如下:取按钮数量+ 1,从顶部开始,设置乘数为buttonCountPlus1:1,然后是buttonCountPlus1:2,最后是buttonCountPlus1:3。(我在下面的旧答案中解释了我从哪里得到这个公式,如果你感兴趣的话)。

5)这里是一个演示运行!

注意:如果你的按钮有较大的高度,那么你需要在常量值中补偿这一点,因为约束是从按钮的底部开始的。


旧的答案


不管苹果的文档和Erica Sadun的优秀书籍(Auto Layout Demystified)说什么,没有间隔器也可以均匀地分隔视图。这在IB和代码中是非常简单的,适用于任意数量的元素。你所需要的是一个数学公式,叫做“剖面公式”。做起来比解释起来简单。我将尽我最大的努力在IB中演示它,但在代码中也很容易做到。

在这个例子中,你会

1)首先设置每个标签有一个中心约束。这很简单。只需从每个标签control拖动到底部。

2)按住shift,因为你也可以添加我们将要使用的另一个约束,即“底部空间到底部布局指南”。

3)选择“bottom space to bottom layout guide”,“在容器中水平居中”。对所有3个标签都这样做。

基本上,如果我们将我们想要确定其坐标的标签除以标签总数加1,那么我们就有一个数字可以加到IB中得到动态位置。我简化了这个公式,但你可以用它来设置水平间距或者同时设置垂直和水平间距。这是超级强大的!

这是乘数。

Label1 = 1/4 = .25,

Label2 = 2/4 = .5,

Label3 = 3/4 = .75

(编辑:@Rivera评论说,你可以简单地直接在乘数字段使用比率,xCode与做数学!)

4)所以,让我们选择Label1,并选择底部约束。是这样的:

5)在属性检查器中选择“第二项”。

6)在下拉菜单中选择“反转第一项和第二项”。

7)将常数归零,wC值为any。(如果需要,可以在这里添加偏移量)。

8)这是关键部分:在乘数字段中添加我们的第一个乘数0.25。

9)当你在它设置顶部的“第一项”为“CenterY”,因为我们想把它居中到标签的y中心。这是所有这些应该看起来的样子。

10)对每个标签重复这个过程,并插入相应的乘数:Label2为0.5,Label3为0.75。这里是最终产品在所有方向与所有紧凑的设备!超级简单。我一直在研究许多涉及大量代码和间隔的解决方案。这无疑是我在这个问题上看到的最好的解决办法。

更新:@kraftydevil补充说底部布局指南只出现在故事板中,而不是在xib中。在xibs中使用'Bottom Space to Container'。好赶上!