将视图隐藏在stackview中仍然可以使约束保持活动状态

时间:2019-05-19 10:40:49

标签: swift uistackview

此代码可以复制粘贴到新创建的项目中:

C1(2)

它是import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label = createLabel() let imageView = createImageView() let stackView = UIStackView(arrangedSubviews: [imageView, label]) stackView.axis = .vertical stackView.spacing = 5 view.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { (_) in imageView.isHidden = true } } func createLabel() -> UILabel { let label = UILabel(frame: .zero) label.text = "Some Text" label.setContentHuggingPriority(.required, for: .horizontal) label.setContentHuggingPriority(.required, for: .vertical) label.backgroundColor = .green return label } func createImageView() -> UIImageView { let imageView = UIImageView() imageView.backgroundColor = .red imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true return imageView } } 内的UILabelUIImageView。当我隐藏UIStackView时,我发现UIImageView正确地适应了UIStackView的高度。但是,UILabel's不能适应UIStackView的宽度。

如何使UILabel调整为仅可见视图/ UIStackView的大小?我为UILabel的高度锚定常量设置了可变变量约束,并在隐藏UIImageView时将其关闭,但是由于某些奇怪的原因,UIImageView消失了。

2 个答案:

答案 0 :(得分:1)

添加堆栈视图alignment

  

此属性确定堆栈视图如何布置其排列   垂直于其轴的视图。默认值为   UIStackView.Alignment.fill。

stackView.alignment = .leading

Stackview将自身调整为唯一可见的UILabel

enter image description here

答案 1 :(得分:0)

尝试将Fill Equally的属性检查器中的分布更改为UIStackView,并根据需要将Alignment更改为Fillcenter