2

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?

Rob N
  • 15,024
  • 17
  • 92
  • 165

2 Answers2

4

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)")
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
1

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)
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • That's useful, but the end result is not exactly what I want because the entire sheet changes width when the text changes. – Rob N Nov 06 '20 at 21:09
  • @RobN Oh, I see now. I added a possible solution but it works in a similar way to Asperi's answer - the goal is to hide the string. – pawello2222 Nov 06 '20 at 21:16