Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to keep a SwiftUI text label from slightly moving while displaying a timer?

Tags:

swift

swiftui

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)
        }
    }
}

Demo GIF

like image 629
M.Serag Avatar asked Dec 08 '22 10:12

M.Serag


2 Answers

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())
like image 200
Gereon Avatar answered Dec 09 '22 23:12

Gereon


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...

like image 29
arsenius Avatar answered Dec 09 '22 23:12

arsenius