Skip to content

Instantly share code, notes, and snippets.

@sowenjub
Created January 24, 2023 09:33
Show Gist options
  • Save sowenjub/5ed3b9f0b924ab461ce7730b4d930de0 to your computer and use it in GitHub Desktop.
Save sowenjub/5ed3b9f0b924ab461ce7730b4d930de0 to your computer and use it in GitHub Desktop.
An extension to display fractions in SwiftUI. This is the answer I posted on https://stackoverflow.com/questions/71359423/how-can-i-show-a-fraction-with-swiftui/75219519#75219519
import SwiftUI
extension UIFont {
static func fractionFont(ofSize pointSize: CGFloat) -> UIFont {
let systemFontDesc = UIFont.systemFont(ofSize: pointSize).fontDescriptor
let featureSettings: [UIFontDescriptor.FeatureKey: Int] = [
.type: kFractionsType,
.selector: kDiagonalFractionsSelector,
]
let attributes = [
UIFontDescriptor.AttributeName.featureSettings: [
featureSettings
]
]
let fractionFontDesc = systemFontDesc.addingAttributes(attributes)
return UIFont(descriptor: fractionFontDesc, size: pointSize)
}
}
extension Font {
static func fraction(_ style: UIFont.TextStyle) -> Font {
let preferredFont = UIFont.preferredFont(forTextStyle: style)
let size = preferredFont.pointSize
return Font(UIFont.fractionFont(ofSize: size) as CTFont)
}
}
struct FontFraction_Previews: PreviewProvider {
static var previews: some View {
Text("1/4")
.font(.fraction(.title1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment