此代码可以复制粘贴到新创建的项目中:
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
}
}
内的UILabel
和UIImageView
。当我隐藏UIStackView
时,我发现UIImageView
正确地适应了UIStackView
的高度。但是,UILabel's
不能适应UIStackView
的宽度。
如何使UILabel
调整为仅可见视图/ UIStackView
的大小?我为UILabel
的高度锚定常量设置了可变变量约束,并在隐藏UIImageView
时将其关闭,但是由于某些奇怪的原因,UIImageView
消失了。
答案 0 :(得分:1)
添加堆栈视图alignment
此属性确定堆栈视图如何布置其排列 垂直于其轴的视图。默认值为 UIStackView.Alignment.fill。
stackView.alignment = .leading
Stackview将自身调整为唯一可见的UILabel
答案 1 :(得分:0)
尝试将Fill Equally
的属性检查器中的分布更改为UIStackView
,并根据需要将Alignment
更改为Fill
或center