I have a simple HStack
containing 2 Text
structs displaying a timer. It keeps changing position slightly while the timer value changes. Is there a way to avoid this behavior.
struct DurationLabel: View {
let majorDuration: String // the hours/minutes part "00:00"
let minorDuration: String // the seconds part "00"
var body: some View {
HStack(spacing: 0) {
Text(majorDuration + minorDuration)
.font(.system(size: 90))
Text(minorDuration)
.font(.body)
}
}
}
For displays like this I prefer to use a font with monospaced digits. You can use them in your Text like so:
Text("your Text here").font(Font.largeTitle.monospacedDigit())
I've done this a number of times for audio players, etc... If you want to keep the same font, you can do something like:
ZStack {
Text("00:00").opacity(0.0)
Text("MM:SS") // Put your actual numbers in here with the same formatting.
}
The ZStack
will size itself based on the largest subview, and 0
is the widest digit in basically any font.
This technique works for any type of content that may change size. Just load up a "dummy" view with the largest possible version and hide it. Then keep your real content in the visible view. Then you can avoid hardcoding a frame size, etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With