Skip to content

Instantly share code, notes, and snippets.

@drewag
Last active June 4, 2020 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewag/0a0738a5c102fb7263a194d842e29f70 to your computer and use it in GitHub Desktop.
Save drewag/0a0738a5c102fb7263a194d842e29f70 to your computer and use it in GitHub Desktop.
SwiftUI view to display normal text as monospaced (fixed width characters)
import SwiftUI
struct MonospacedText: View {
let content: String
let characterWidth: CGFloat
init(_ content: String, characterWidth: CGFloat) {
self.content = content
self.characterWidth = characterWidth
}
var body: some View {
HStack(spacing: 0) {
ForEach(0..<self.content.count, id: \.self) { index in
Text("\(self.content[self.content.index(self.content.startIndex, offsetBy: index)].description)")
.frame(width: self.characterWidth)
}
}
}
}
struct MonospacedText_Previews: PreviewProvider {
static var previews: some View {
MonospacedText("12:34:56:78:90", characterWidth: 20)
.font(.largeTitle)
.foregroundColor(.purple)
}
}
@drewag
Copy link
Author

drewag commented Jun 4, 2020

I'm using this view to display a count down that doesn't jump around every time a number changes. If you see any way to improve its implementation, especially to automatically calculate the maximum glyph size for the current font, I'd love to know!

@drewag
Copy link
Author

drewag commented Jun 4, 2020

Apparently Font in SwiftUI has a monospacedDigit modifier. That's better than this solution if it is only for digits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment