当我以编程方式添加一个没有约束的子视图时会发生什么?

What happens when I programatically add a subview without constraints?

我经常遇到类似 view.addSubview(myAwesomeTableView) 的事情。

显然,Auto Layout 中没有设置约束。那么系统如何确定如何放置以及放置在何处myAwesomeTableView。它会简单地匹配父视图的大小吗?

另外 translatesAutoresizingMaskIntoConstraints 与此有什么关系?

默认每UIView帧为CGRect.zero.

如果启用translatesAutoresizingMaskIntoConstraints(默认启用),您可以使用autoresizingMask,系统会为您生成约束。

Read more about the autoresizingMask property here.

So how does the system determine how and where to place myAwesomeTableView. Will it simply match the size of the parent view?


基本上,它取决于myAwesomeTableView(子视图)frame。添加子视图时,会自动添加到(0,0)原点,所以子视图框架为:

x: 0
y: 0
width: subview width.
height: subview height.

注意,如果subview frame未定,宽高默认为0


what does translatesAutoresizingMaskIntoConstraints have to do with this?


改编自 translatesAutoresizingMaskIntoConstraints 文档:

A Boolean value that determines whether the view’s autoresizing mask is translated into Auto Layout constraints.

这意味着系统会创建一组约束来复制视图的自动调整大小掩码指定的行为,您将能够通过编辑其帧值直接修改所需的视图位置(原点)和大小。

注意:

By default, the property is set to true for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to false.

在以编程方式向视图添加约束时,请注意,您必须将 translatesAutoresizingMaskIntoConstraints 设置为 false:

myView.translatesAutoresizingMaskIntoConstraints = false

表示"I will handle the constraint of the view by my self",否则不会激活添加的约束。

此外,您可能需要检查: