我通过这种方式在视图控制器中添加了一个stackView:
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.anchor(top: nameLabel.bottomAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor)
let emotionsButton = EmotionButton()
emotionsButton.translatesAutoresizingMaskIntoConstraints = false
let contentButton = ContentsButton()
contentButton.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 8
stackView.addArrangedSubview(emotionsButton)
stackView.addArrangedSubview(contentButton)
emotionsButton.widthAnchor.constraint(equalToConstant: 91).isActive = true
contentButton.widthAnchor.constraint(equalToConstant: 91).isActive = true
emotionsButton.heightAnchor.constraint(equalToConstant: 83).isActive = true
contentButton.heightAnchor.constraint(equalToConstant: 83).isActive = true
但是我得到的结果不是想要的结果;这就是我想要的:
这就是我得到的:
答案 0 :(得分:1)
如果要在stackview上执行此操作,则无需相应地配置子视图的heightAnchor或widthAnchor(emotionsButton,contentButton)。您只需配置 stackView的高度和宽度锚点即可。 ,并让其相应地调整子视图的大小。
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 8
stackView.widthAnchor.constraint(equalToConstant: 91 * 2).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 83).isActive = true
stackView.addArrangedSubview(emotionsButton)
stackView.addArrangedSubview(contentButton)
答案 1 :(得分:1)
UIStackView
尝试用其内容填充整个宽度。所以你在这里有一些选择
由于stackView的内容大小取决于其内容,因此您应该考虑摆脱leading
和trailing
锚点,而改为使用水平中心。 (您可以将其中一个与中间的一个并排放置,以防止其与边缘重叠)
另一个选择是添加。堆栈视图两侧(内部)的虚拟视图,使它们具有clear
颜色,并使其成为最后一个拥抱。所以。他们。能够。填充额外的空间。
您可以实施其他选项(例如根本不使用堆栈视图)。
答案 2 :(得分:1)
更改优先级为.required
的内容。
stackView.setContentHuggingPriority(.required, for: .horizontal)