Ios 水平自动布局约束

Ios 水平自动布局约束,ios,swift,autolayout,Ios,Swift,Autolayout,在UITableViewCell的子类中,我尝试使用自动布局 以下是我想做的: 这是我的代码,但它不起作用:只显示一个视图 import Foundation class CustomCell: UITableViewCell { func configureCell() { backgroundColor = UIColor.yellowColor() let redColorView = UIView() redColorVi

在UITableViewCell的子类中,我尝试使用自动布局

以下是我想做的:

这是我的代码,但它不起作用:只显示一个视图

import Foundation

class CustomCell: UITableViewCell {

    func configureCell() {

        backgroundColor = UIColor.yellowColor()

        let redColorView = UIView()
        redColorView.backgroundColor = UIColor.redColor()
        redColorView.translatesAutoresizingMaskIntoConstraints = false

        let blueColorView = UIView()
        blueColorView.backgroundColor = UIColor.blueColor()
        blueColorView.translatesAutoresizingMaskIntoConstraints = false

        addSubview(blueColorView)
        addSubview(redColorView)

        let viewsDictionary = ["blue":blueColorView,"red":redColorView]

        let layout = NSLayoutFormatOptions(rawValue: 0)

        let horizontalContraint:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("|-10-[blue]-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)

        let verticalContraint_1:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[blue]-10-|", options: layout, metrics: nil, views: viewsDictionary)

        let verticalContraint_2:[NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:|-10-[red]-10-|", options: layout, metrics: nil, views: viewsDictionary)

        self.addConstraints(verticalContraint_1)
        self.addConstraints(verticalContraint_2)
        self.addConstraints(horizontalContraint)
    }
}

问题是您的水平约束不明确。它们不足以解析为一个布局。因此,系统必须从各种可能性中任意选择

特别是,
-10-[blue]-10-[red]-10-[code>没有指定
blue
red
的宽度。假设superview的宽度大于30点,则可以使用任意数量的解决方案<代码>蓝色
可以是0宽度,
红色
可以是superview的宽度减去30。反之亦然。或者介于两者之间的任何东西。对两个子视图宽度的唯一有效约束是,它们加起来等于superview的宽度减30。既然您说只有一个是可见的,那么另一个大概被指定为0宽度

正如您所注意到的,您可以显式地约束子视图的宽度,或者指定它们彼此具有相等的宽度(或其他比例)


如果视图具有固有大小,或者如果它们具有固有大小的子视图,并且它们的宽度基于它们的子视图而受到约束,那么内容拥抱和抗压缩优先级之类的事情就会起作用。但是像您正在使用的普通
UIView
s没有固有的大小,所以它们没有。

谢谢,我试着做ASCII艺术,但长(丑)的方法是,您是否开始使用
Constraints with VisualFormat
?我也许能弄明白这一点,但以前从未使用过。您是否尝试过设置约束以使两个视图具有相等的宽度?我很熟悉以编程方式设置约束,但使用
InterfaceBuilder
,这将非常容易。我刚刚发现设置“|-10-[blue(50)]-10-[red]-10-[blue(red)]-10-[red]-10-[red]-10-[red]-10-|”是可行的。我认为应该为其中一个视图设置一个大小?我相信您只应该根据superview中剩余的空间设置其中一个视图的大小。所以,如果你说让红色=蓝色的宽度,让蓝色自动调整大小,以适应它将工作