How do I work with UIStackView effectively in Swift?

Working with UIStackView in Swift allows developers to create responsive and flexible layouts with minimal code. UIStackView simplifies the process of aligning and distributing views within a container, making it an essential tool for any iOS developer.

Example of UIStackView

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Create a vertical stack view let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 10 stackView.alignment = .center stackView.distribution = .fillEqually // Create some views to add to the stack let view1 = UIView() view1.backgroundColor = .red let view2 = UIView() view2.backgroundColor = .green let view3 = UIView() view3.backgroundColor = .blue // Add views to the stack view stackView.addArrangedSubview(view1) stackView.addArrangedSubview(view2) stackView.addArrangedSubview(view3) // Set stack view constraints (assuming you want it centered) stackView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(stackView) NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor), stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor), stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5), ]) } }

UIStackView iOS development Swift layout responsive design