Reputation: 13043
This code can be copy paste inside a newly created project:
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
}
}
It is a UILabel
and a UIImageView
inside a UIStackView
. When I hide the UIImageView
, I see that the UIStackView
correctly adapts itselfs to the UILabel's
height. However, the UIStackView
does not adapts itself to the width of the UILabel
.
How can I make the UIStackView
resize itself to it's only visible views/UILabel
? I made a variabele constraint for the UIImageView
's height anchor constant and turning that off when hiding the UIImageView
, but than the UILabel
disappears for some odd reason.
Upvotes: 0
Views: 46
Reputation: 206
Try changing the Distribution to Fill Equally
in the UIStackView
's Attribute Inspector and the Alignment
to Fill
or to center
as you like it to be.
Upvotes: 0
Reputation: 15758
Add stackview alignment
This property determines how the stack view lays out its arranged views perpendicularly to its axis. The default value is UIStackView.Alignment.fill.
stackView.alignment = .leading
Stackview resizes itself to it's only visible UILabel
Upvotes: 1