Created
July 18, 2020 07:01
-
-
Save byaruhaf/86ea807cce82d15b6b2570093255e3f7 to your computer and use it in GitHub Desktop.
A SwiftUI View used to display strings with subscripted text
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 SubscriptedTextView: View { | |
// MARK: Properties | |
let abbreviation: String | |
var body: some View { | |
subscriptedText() | |
} | |
// MARK: Helpers | |
private func subscriptedText() -> Text { | |
let mainFont = Font.body | |
var texts = [Text]() | |
abbreviation.forEach { character in | |
let characterString = String(character) | |
if let _ = Int(characterString) { | |
let subscriptText = Text(characterString).font(.caption2).baselineOffset(UIFont.preferredFont(forTextStyle: .body).pointSize / -4) | |
texts.append(subscriptText) | |
} else { | |
let normalText = Text(characterString).font(mainFont) | |
texts.append(normalText) | |
} | |
} | |
return texts.reduce(Text(""), +) | |
} | |
} | |
struct ParameterAbbreviationView_Previews: PreviewProvider { | |
static var previews: some View { | |
Group { | |
ParameterAbbreviationView(abbreviation: "Ca") | |
ParameterAbbreviationView(abbreviation: "PO4") | |
ParameterAbbreviationView(abbreviation: "H2PO4") | |
} | |
.previewLayout(.sizeThatFits) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment