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 hidden or 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Apparently
Fontin SwiftUI has amonospacedDigitmodifier. That's better than this solution if it is only for digits.