美文网首页
Preserves Superview Layout Margi

Preserves Superview Layout Margi

作者: 内蒙小猿 | 来源:发表于2020-12-28 15:06 被阅读0次

preservesSuperviewLayoutMargins 如何使用

获取代码

UIView Layout Margins

我们简单的把 redView 直接固定在 ViewController 上,yellowView 通过 margins 固定到 redView 上,如下图。


1.png

Note: 在iOS 11之前无法更改根视图的边距。因为系统会根据类大小自动设置根视图的边距。上 margins 和下 margins 为 0 ,前后 margins 为 16 或 20 ,具体取决于尺寸类别。

Preventing Content in the Superview Margin

superview 的 margins 是 16pt, yellowView 到 redView 的 margins 是 8 pt, 这种情况下 superview 和 yellowView 的 margins 重叠了,并且 yellowView 的 margins 小于 superview 的 margins。 我们再来看下官方文档截取:

When the value of this property is YES, the superview’s margins are also considered when laying out content. This margin affects layouts where the distance between the edge of a view and its superview is smaller than the corresponding margin.

2.png

现在设置 redView:

 redView.preservesSuperviewLayoutMargins = true

为了明显 Root View margins 设置的大一些:

self.view.layoutMargins = UIEdgeInsets (top: 50 , left: 50, bottom: 50, right: 50)
comparison.png

结果已经很明显了 preservesSuperviewLayoutMargins 为 true 时,yellow 到 red 的边距增加了。

Note: 属性生效的特定情形

1、容器视图以 edge 进行约束.
2、内容视图以 margins 进行边距约束.
3、容器视图的的 margins 小于其父视图的 margins

如果所有的 View 都是通过 edge 进行约束而非 margins ,那么 preservesSuperviewLayoutMargins 就不会生效了。

Stack View - Using Margins

UIStackView 有点特殊,默认情况下通过 addArrangedSubview 添加的 views ,是直接通过 edge 进行约束。我们需要通过更改代码进行适配:

stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets (top: 3, left: 3, bottom: 3, right: 3)
stackView.preservesSuperviewLayoutMargins = true
UIStackVIew - preserver.png

相关文章

网友评论

      本文标题:Preserves Superview Layout Margi

      本文链接:https://www.haomeiwen.com/subject/rzgznktx.html