Skip to content

Instantly share code, notes, and snippets.

@byaruhaf
Created July 18, 2020 07:01
Show Gist options
  • Save byaruhaf/86ea807cce82d15b6b2570093255e3f7 to your computer and use it in GitHub Desktop.
Save byaruhaf/86ea807cce82d15b6b2570093255e3f7 to your computer and use it in GitHub Desktop.
A SwiftUI View used to display strings with subscripted text
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