Post

SwiftUI Trick. How to align a list of numbers with different sizes.

Sometimes you want to show a title with a background in a list, for example, and you have a problem with the size of the background. Imagine that you want to show a digit but when you change the number 9 for the number 10, the background size becomes greater than the previous.

The solution

There is a trick in this context and this is so simple. You need to put a ZStack with a hidden view.

1
2
3
4
5
6
7
8
9
10
11
ZStack(alignment: .trailing) {
    Text("999")
        .hidden()
    Text("140") // or 14, roundrectangle will have same width
}
.padding(.horizontal)
.padding(.vertical, 4)
.background {
    RoundedRectangle(cornerRadius: 8, style: .continuous)
        .fill(.regularMaterial)
}
This post is licensed under CC BY 4.0 by the author.