I am trying to represent a fraction with denominator larger than 9 in a SwiftUI Text.
I can implement this using individual elements and applying offsets but that get’s a bit messy as the fractions change dynamically.
Is there a way to do this using attributedText?
I came across thi UIFont extension with deprecated methods and wondering if anything similar that can be used with SwiftUI:
extension UIFont {
static func fractionFont(ofSize pointSize: CGFloat) -> UIFont {
let systemFontDesc = UIFont.systemFont(ofSize: pointSize).fontDescriptor
let fractionFontDesc = systemFontDesc.addingAttributes(
[
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kFractionsType,
UIFontDescriptor.FeatureKey.typeIdentifier: kDiagonalFractionsSelector,
], ]
] )
return UIFont(descriptor: fractionFontDesc, size:pointSize)
}
}
2
Answers
UIFont
is toll-free-bridged withCTFont
, which means you can cast aUIFont
to aCTFont
by sayingas CTFont
. And SwiftUI’sFont
has an initializer that takes aCTFont
.So, using the
fractionFont(ofSize:)
method you posted, this playground code:produces this result:
Building on this, here’s a version without the deprecations that takes a
UIFont.TextStyle
for parameter, allowing you to simply do this:Here are the extensions you need: