上边距(自动布局)

问题描述 投票:1回答:1

我为白色矩形(视图)设置了右边距 - 1.008

enter image description here

现在我想设置Top Margin - 1.1,但没有任何变化(无论我为Multiplier设置的是什么),white rect仍然位于黑色rect的顶部,没有任何边距:

enter image description here

附:我不想使用常量(我想设置百分比的边距取决于父视图,似乎乘数是为此而设计的)

更新(我想要的例子)

enter image description here

ios autolayout
1个回答
1
投票

Autolayout在这里按预期工作。你的问题是一个简单的数学问题。你的superview top位于0,对于你的约束,这是成立的(阅读更多关于约束解剖学here):

yourView.top = multiplier * superView.top + constant

填写值后:

yourView.top = 0 * 1.1 + 0

这很简单:

yourView.top = 0

在你的问题中,正确的间距是有效的,因为superView.right绝对大于0(从我在图片上看到的,它接近UIScreen.main.bounds.width)。

更新

为了得到你想要的东西,我通常建议使用UILayoutGuide,但由于你使用的是故事板(不支持),你必须添加一个虚拟透明的UIView

获得你想要的东西的布局需要看起来像这样(我使用.red颜色而不是.clear,这样你就可以看到我想要实现的目标):

enter image description here

在这种情况下,您需要设置以下约束。我将使用编程方式设置它们,但我相信您可以轻松阅读它们并将它们转换为故事板:

首先,将透明(在我的视图中为红色)虚拟视图约束到黑色视图的右上角 - blackView):

// by default constant = 0, multiplier = 1
dummyView.topAnchor.constraint(equalTo: blackView.topAnchor).isActive = true
// right or trailing, it's up to you
dummyView.rightAnchor.constraint(equalTo: blackView.rightAnchor).isActive = true

然后将dummyView约束为一个完美的正方形(宽度等于高度):

// by default constant = 0, multiplier = 1
dummyView.widthAnchor.constraint(equalTo: dummyView.heightAnchor).isActive = true

保持whiteView的右侧约束,并用它来确定dummyView的大小:

dummyView.leftAnchor.constraint(equalTo: whiteView.leftAnchor).isActive = true

在此之后,dummyView将具有offset x offset的大小,因为它的左侧被限制为whiteView.right,而它的右侧被限制为blackView.right

所以现在你完成最后一个约束,它将从顶部正确定位whiteView

whiteView.topAnchor.constraint(equalTo: dummyView.bottomAnchor).isActive = true
© www.soinside.com 2019 - 2024. All rights reserved.