Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Text jiggling in SwiftUI

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)
}
like image 982
Facundo Luis Rodriguez Avatar asked Dec 31 '22 16:12

Facundo Luis Rodriguez


1 Answers

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.

like image 124
John M. Avatar answered Jan 05 '23 17:01

John M.