我目前正在将UIImageView的宽度和高度限制固定为20,并将UIView置于该UIImageView的下面。但是UIView的宽度为20,与UIImageView相同,但是当我向UIView添加宽度约束10时,UIImageView变为10x10 ...下面是我的实现:-
guard let superview = superview else { return }
verticalStack = UIStackView()
verticalStack?.translatesAutoresizingMaskIntoConstraints = false
verticalStack?.isLayoutMarginsRelativeArrangement = true
verticalStack?.axis = .vertical
verticalStack?.backgroundColor = UIColor.green
verticalStack?.spacing = 5.0
brightnessIcon = UIImageView(image: UIImage(named: "brightness.png"))
brightnessIcon?.contentMode = .scaleAspectFit
brightnessIcon?.widthAnchor.constraint(equalToConstant: 20.0).isActive = true
brightnessIcon?.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
verticalStack?.addArrangedSubview(brightnessIcon!)
brightnessIndicator = UIView()
brightnessIndicator?.backgroundColor = UIColor.red
brightnessIndicator?.widthAnchor.constraint(equalToConstant: 5.0).isActive = true
verticalStack?.addArrangedSubview(brightnessIndicator!)
下面是在我将宽度约束添加到BrightnessIndicator(UIView)之前的图像:-
在向BrightnessIndicator添加宽度约束之后:-
答案 0 :(得分:0)
您必须更改stackView的alignment
。默认情况下,此设置为fill
,它会尝试布局排列的子视图以填充stackView的相反轴(在您的情况下,它们将被填充horizontally
)。
尝试将对齐方式设置为leading
,trailing
或centered
(您必须自己检查一下是否适合您的需求)。由于这些对齐方式选项不会强制调整排列的子视图的大小。
答案 1 :(得分:0)
您需要设置stackView的分布和对齐方式
verticalStack?.translatesAutoresizingMaskIntoConstraints = false
verticalStack?.isLayoutMarginsRelativeArrangement = true
verticalStack?.axis = .vertical
verticalStack?.alignment = .center
verticalStack?.distribution = .fillProportionally