7

Any idea to avoid the jiggling below? The code is something like this:

Text(format: "%02d:%02d", hours, minutes)
    .frame(width: 100, alignment: .trailing)

jiggling

(The frame is bigger than the string)

NOTES:

  • The problem is that "1" is thinner than "0" so when I hit a combination like 01:11 the total length of the string is smaller than (let's say) 00:00 and the text is displaced.
  • Fixing the frame width has no effect on the jiggling.
  • Alignment .trailing or .center don't fix the jiggling.
  • I am curious about the ... that appears from time to time. I can fix it by adding a whitespace at the end of the String like this "%02d:%02d "

The slider code (for completion):

Slider(value: $totalTime, in: 0...9).frame(width: 150)

The conversion from Slider value to hh:mm:

func formatTime(_ time: Float) -> String {
    let hours: Int = Int(time)
    let minutes: Int = Int(time.truncatingRemainder(dividingBy: 1.0) * 60)

    return String(format: "%02d:%02d", hours, minutes)
}
  • 1
    Why not just set a fixed `minWidth`? – LinusGeffarth Sep 13 '19 at 12:22
  • Welcome to StackOverflow. Can you please post a more complete code snippet? Ideally it should be everything in the `View` – Zain Sep 13 '19 at 13:34
  • I can see the same issue in apps like itunes. The difference is that their font is very small so it might not be important. In my case, the text has a bigger font, so the jiggling is quite obvious – Facundo Luis Rodriguez Sep 13 '19 at 13:54
  • Hi @LinusGeffarth... Yes I tried with minWidth and width, but no success – Facundo Luis Rodriguez Sep 13 '19 at 13:57
  • You could always use a monospace font :P – Quinn Sep 13 '19 at 15:09
  • This looks similar to an issue I had when text is changing and animating simultaneously (FB7253222). Any chance you have animation associated with that text view? If so, try removing the animation and see if that fixes it. You should be able to target the animations on the views that need it so the text can lay out properly. – smr Sep 13 '19 at 20:20

1 Answers1

14

You can tell it to use monospace digits like this:

Text(String(format: "%02d:%02d", hours, minutes))
    .font(Font.body.monospacedDigit())
    .frame(width: 100, alignment: .trailing)

You can substitute "Font.body" with your preferred Font.

John M.
  • 8,892
  • 4
  • 31
  • 42