如何在iOS中的UIStackView中设置权重 [英] How to set weight in UIStackView in IOS
问题描述
UIStackView
与Android LinearLayout
类似,但是我不知道如何为子视图设置权重.
UIStackView
is similar to Android LinearLayout
but I could not figure out how to set weight for the subviews.
假设我有一个垂直的UIStackView
和3个UIImageView
.我想连续为UIImageView
设置权重3、6、1.我该怎么办?
Suppose I have a vertical UIStackView
and 3 UIImageView
s in it. I want to set weights 3, 6, 1 consecutively for the UIImageView
s. How do I do that?
推荐答案
UIStackView
具有不同的权重概念.它可以使用子视图的intrinsicContentSize
作为权重,但是设置特定的intrinsicContentSize
通常需要创建一个子类,并且它也可以在其他情况下使用(与您熟悉的android:layout_weight
属性不同,该属性仅由LinearLayout
).
UIStackView
doesn't have the same concept of weights. It can use a subview's intrinsicContentSize
as a weight, but setting a specific intrinsicContentSize
typically requires making a subclass and it's used in other situations too (unlike the android:layout_weight
attribute you're familiar with, which is only used by LinearLayout
).
但是,由于UIStackView
通过将约束应用于其排列的子视图而起作用,因此可以通过在子视图的高度之间设置其他约束来获得权重的效果. (UIStackView
旨在让您添加自己的约束以这种方式调整布局.)
But since UIStackView
works by applying constraints to its arranged subviews, you can get the effect of weights by setting additional constraints between the heights of the subviews. (UIStackView
is designed to let you add your own constraints to tweak the layout this way.)
在您的情况下,您希望将顶视图的高度限制为底视图的高度的3倍,并且希望将中间视图的高度限制为底视图的高度的6倍.
In your case, you want to constrain the height of the top view to be 3 times the height of the bottom view, and you want to constrain the height of the middle view to be 6 times the height of the bottom view.
您可以通过创建等宽约束,然后编辑约束的乘数来在情节提要中设置比例高度约束.
You can set up a proportional-height constraint in a storyboard by creating an equal-width constraint, then editing the constraint's multiplier.
在代码中,您可以这样做(在iOS 9.0或更高版本上):
In code, you could do it like this (on iOS 9.0 or later):
NSLayoutConstraint.activateConstraints([
top.heightAnchor.constraintEqualToAnchor(bottom.heightAnchor, multiplier: 3),
middle.heightAnchor.constraintEqualToAnchor(bottom.heightAnchor, multiplier: 6),
])
这篇关于如何在iOS中的UIStackView中设置权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!