You are assuming each character is equally wide. That is only true for monospace fonts. You can get the default monospaced font by using UIFont.monospacedSystemFont:
If you don’t want to change the font, a simple solution would be to put the "-" character into another UILabel. This way, you can constraint all the labels on the left to have the same width, and that the "-" labels would be on the right of them.
An example of doing this with UIStackViews:
func makeLabel(_ text: String) -> UILabel {
let label = UILabel()
label.text = text
label.font = UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular)
return label
}
func makeHStack(_ text: String) -> UIStackView {
let stackView = UIStackView(arrangedSubviews: [makeLabel(text), makeLabel("-")])
stackView.axis = .horizontal
NSLayoutConstraint.activate([
// freely adjust this 0.4 ratio
stackView.arrangedSubviews[0].widthAnchor.constraint(equalTo: stackView.widthAnchor, multiplier: 0.4)
// making the width equal to a constant is also an option
])
return stackView
}
// constructing the 3 rows and placing them into a superview
let vstack = UIStackView(arrangedSubviews: [makeHStack("Name"), makeHStack("Class"), makeHStack("Reason")])
vstack.axis = .vertical
view.addSubview(vstack)
vstack.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
vstack.widthAnchor.constraint(equalTo: view.widthAnchor),
vstack.centerXAnchor.constraint(equalTo: view.centerXAnchor),
vstack.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
This should line up the hyphens. Depending on the font you might need more or less t (tab) characters in a given label than the others to get it to line up.
2
Answers
You are assuming each character is equally wide. That is only true for monospace fonts. You can get the default monospaced font by using
UIFont.monospacedSystemFont
:If you don’t want to change the font, a simple solution would be to put the "-" character into another
UILabel
. This way, you can constraint all the labels on the left to have the same width, and that the "-" labels would be on the right of them.An example of doing this with
UIStackView
s:There’s a simple solution – replace the spaces with tabs. No need for monospaced fonts or stack views.
Start with:
This should line up the hyphens. Depending on the font you might need more or less
t
(tab) characters in a given label than the others to get it to line up.