UIStackView:添加具有相同宽度的排列视图

UIStackView: add arranged views with the same width

我有 UIStackView 并想向此视图添加一些排列的视图...有时是一个,有时是两个,三个...等。UIStackView 具有全宽。我希望排列的视图具有与左对齐相同的宽度,这样它们就不会填满 UIStackView 的整个宽度。

这是我的:

这就是我想要的:

是否有可能以某种方式做到这一点,或者我是否需要根据我添加的排列数量来更改 UIStackVIew 的宽度?

我的代码:

        // creating views
    stackView = {
        let v = UIStackView()
        v.axis = .horizontal
        v.alignment = .center
        v.distribution = .fillEqually
        v.spacing = 5
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
 if let img = chosenImage {
            let imageView: UIImageView = {
                let l = UIImageView()
                l.translatesAutoresizingMaskIntoConstraints = false
                l.image = img
                return l
            }()
            self.stackView?.addArrangedSubview(imageView)
            imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1, constant: 1))
            imageView.setNeedsUpdateConstraints()
        } else {
            print("Something went wrong")
        }

您可以在最后为您的 StackView 添加一个空的清晰视图,并为此视图设置拥抱和阻力优先级。它应该调整到可用 space 所以 "fill view" 的拥抱优先级必须更高并且 "fill view" 的阻力应该很低,在你的真实物品上设置更高的阻力值

在故事板上,Select stackview,属性检查器 -> Stackview -> 分布,select 均匀填充。