I created a simple vertical stack view containing 3 subview with different width.
I pin the stack view to top left of the parent and did not specify width on purpose.
I expect the stack view to use the width of the largest subview as its width. As stated from apple doc: https://developer.apple.com/documentation/uikit/uistackview
Quote:
Perpendicular to the stack view’s axis, its fitting size is equal to the size of the largest arranged view.
but the result looks like the stackview uses the width of the smallest subview.
I don’t understand why the code behave this way.
Here is my code:
import Foundation
import UIKit
import SwiftUI
import SnapKit
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Create the stack view with a vertical axis
let stackView = UIStackView()
stackView.axis = .vertical
stackView.backgroundColor = .gray
stackView.spacing = 20
stackView.alignment = .fill // Change this to .leading to see the effect
stackView.translatesAutoresizingMaskIntoConstraints = false
// Add the stack view to the view controller's view
view.addSubview(stackView)
// Constraints for the stack view
stackView.snp.makeConstraints { make in
make.top.equalTo(view)
make.left.equalTo(view)
}
// Create three views with different widths
let view1 = UIView()
view1.translatesAutoresizingMaskIntoConstraints = false
view1.backgroundColor = .red
view1.snp.makeConstraints { make in
make.width.equalTo(100)
make.height.equalTo(50)
}
let view2 = UIView()
view2.translatesAutoresizingMaskIntoConstraints = false
view2.backgroundColor = .green
view2.snp.makeConstraints { make in
make.width.equalTo(200)
make.height.equalTo(50)
}
let view3 = UIView()
view3.translatesAutoresizingMaskIntoConstraints = false
view3.backgroundColor = .blue
view3.snp.makeConstraints { make in
make.width.equalTo(300)
make.height.equalTo(50)
}
// Add views to the stack view
stackView.addArrangedSubview(view2)
stackView.addArrangedSubview(view1)
stackView.addArrangedSubview(view3)
}
}
struct TestViewControllerTestView : UIViewControllerRepresentable {
typealias UIViewControllerType = TestViewController
func makeUIViewController(context: Context) -> TestViewController {
return TestViewController()
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}
struct TestViewController_Preview : PreviewProvider {
static var previews: some View {
TestViewControllerTestView()
}
}