当给予相等宽度约束按钮时,自动布局设置不正确

时间:2016-10-05 13:30:42

标签: ios autolayout

我看到很多解决方案并应用了自动布局约束,但我仍然没有得到理想的解决方案。

当前结果:

Result after Auto layout set

给所有按钮的约束:

Constrains given to buttons

查看层次结构:

enter image description here

3 个答案:

答案 0 :(得分:0)

对不起代码中的解决方案.. .Swift 3.0:

    let button1 = UIButton()
    let button2 = UIButton()
    let button3 = UIButton()
    let buttons = [button1, button2, button3]
    button1.backgroundColor = .red
    button2.backgroundColor = .blue
    button3.backgroundColor = .green
    buttons.forEach {
        $0.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview($0)
    }
    buttons.forEach {
        let cnt1 = NSLayoutConstraint(item: $0, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
        let cnt2 = NSLayoutConstraint(item: $0, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 0.2, constant: 0)
        view.addConstraints([cnt1, cnt2])
    }
    let cnt1 = NSLayoutConstraint(item: button1, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    let cnt2 = NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: button3, attribute: .trailing, multiplier: 1, constant: 0)
    let cnt3 = NSLayoutConstraint(item: button2, attribute: .width, relatedBy: .equal, toItem: button1, attribute: .width, multiplier: 1, constant: 0)
    let cnt4 = NSLayoutConstraint(item: button3, attribute: .width, relatedBy: .equal, toItem: button2, attribute: .width, multiplier: 1, constant: 0)
    let cnt5 = NSLayoutConstraint(item: button2, attribute: .leading, relatedBy: .equal, toItem: button1, attribute: .trailing, multiplier: 1, constant: 0)
    let cnt6 = NSLayoutConstraint(item: button3, attribute: .leading, relatedBy: .equal, toItem: button2, attribute: .trailing, multiplier: 1, constant: 0)
    view.addConstraints([cnt1, cnt2, cnt3, cnt4, cnt5, cnt6])

答案 1 :(得分:0)

您是否尝试水平布置三个具有相同高度和宽度的按钮?我认为你可以在不使用UIViews的情况下实现这一目标。我设置如下约束。

enter image description here

这是一个模拟器截图。

Simulator screenshot

答案 2 :(得分:0)

假设您想要的是让3个按钮彼此相等并使用Interface Builder填充屏幕宽度(没有代码,即:不是以编程方式),这是一个解决方案:

您无需在视图中添加它们。只需按照以下步骤操作:

让我们从这开始:

enter image description here

请注意,按钮没有任何约束 - 只是 - 只需将它们添加到视图的底部(或者您想要显示它们的位置),对于此解决方案,我将在底部显示它们屏幕)。确保它们中的3个具有相同的大小。

橙色按钮添加约束:

添加以下约束: 领先,底部空间和相等的高度。

enter image description here

blue 按钮添加约束:

添加以下约束: 尾随,底部空间和相等的高度。

enter image description here

青色按钮添加约束:

  • 按住Ctrl键并从青色按钮拖动到橙色按钮并添加以下约束:水平间距和垂直居中。

enter image description here

  • ctrl +从青色按钮拖动到蓝色按钮并添加以下约束:水平间距。

enter image description here

  • 底部空间和相等的高度。

enter image description here

到目前为止,我们差不多完成了!

现在,选择3个按钮并添加以下约束:等宽。

enter image description here

您的按钮应如下所示:

enter image description here

现在,您所要做的就是选择两个水平间距约束中的每一个,并将它们的常量设置为0 - 来自尺寸检查器 - :

enter image description here

enter image description here

你去了:

enter image description here

我希望这有所帮助,干杯。