Last active
June 4, 2020 23:56
-
-
Save drewag/0a0738a5c102fb7263a194d842e29f70 to your computer and use it in GitHub Desktop.
SwiftUI view to display normal text as monospaced (fixed width characters)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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) | |
} | |
} |
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
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!