create two labels side by side with adjustable width in swift

One way to create two labels side by side with adjustable width is to use UIStackView with fillEqually distribution. Here's how to do it programmatically:

main.swift
// Create stack view
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)

// Create first label
let label1 = UILabel()
label1.text = "Label 1"
label1.textAlignment = .center
label1.backgroundColor = .red
label1.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(label1)

// Create second label
let label2 = UILabel()
label2.text = "Label 2"
label2.textAlignment = .center
label2.backgroundColor = .blue
label2.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(label2)

// Add constraints to stack view
NSLayoutConstraint.activate([
    stackView.topAnchor.constraint(equalTo: view.topAnchor, constant: 16),
    stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
    stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
])
990 chars
31 lines

Here, we've created a horizontal stack view with two labels as arranged subviews. The fillEqually distribution makes sure that both labels have equal width. The spacing property adds some space between the labels. Finally, we've added constraints to position the stack view at the top-left with some padding. You can adjust the padding and other properties as needed.

gistlibby LogSnag