create a stackview with two labels in swift

You can create a stack view with two labels using the UIStackView class provided by iOS. The UIStackView provides an easy way to layout views horizontally or vertically in a flexible way.

First, create two UILabel instances with the desired text:

main.swift
let label1 = UILabel()
label1.text = "Label 1"
let label2 = UILabel()
label2.text = "Label 2"
94 chars
5 lines

Then, create a UIStackView instance and add the labels to it:

main.swift
let stackView = UIStackView(arrangedSubviews: [label1, label2])
stackView.axis = .vertical // or .horizontal, depending on your needs
stackView.alignment = .fill
stackView.distribution = .fill
193 chars
5 lines

Finally, add the stack view to your view hierarchy and set up the necessary constraints:

main.swift
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    stackView.topAnchor.constraint(equalTo: view.topAnchor),
    stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
387 chars
9 lines

This will create a stack view with two labels arranged vertically and filling the available space. You can customize the appearance and layout of the labels by setting their properties, such as font, color, and constraints.

gistlibby LogSnag