How to reserve space for Text in SwiftUI

Viewed 216

I have a sheet that shows progress for uploading files. It looks like this:

As you can see, the line that changes ("3.4 MB of 13.9...") gets truncated. This is because it starts off with one width, but then can grow with different numbers in the string.

I tried the following, as a trick to reserve space for the biggest string possible. It works, but is not ideal, because the white Rectangle won't work in dark mode.

VStack(spacing: 0) {
    Text("Uploading").bold()
    Spacer().frame(height: 3)
    Text("\(currentFilename)")
    Text("\(completedFiles) of \(totalFiles) files")
    ZStack {
        Text("12345 KB of 12345 KB")    // Biggest possible string
        Rectangle().fill(Color.white)   // But how to hide it ?            
        Text("\(bytes) of \(totalBytes)")
    }
    ProgressView(value: fraction)
    Button("Cancel") { ... }        
}.padding()

I don't see a Color.systemBackgroundColor or similar to substitute for the Color.white.

Anyone know a good trick like this to reserve space for text? Either with my ZStack idea or something else?

2 Answers

If it helps you use Color.clear

ZStack {
    Text("12345 KB of 12345 KB")    // Biggest possible string
       .foregroundColor(Color.clear)    // << here !!
    Text("\(bytes) of \(totBytes)")
}

You can try fixedSize:

Text("\(bytes) of \(totalBytes)")
    .fixedSize()

Then you don't need hacks like Text("12345 KB of 12345 KB")


If you want to keep the width constant you can do:

Text("12345 KB of 12345 KB")
    .opacity(0)
Related