Alex Alex - 19 days ago 5
Swift Question

Is there a neat way to represent a fraction as an attributed string?

i was wondering if there was a builtin method to represent

var someFraction = "1/12"


as an attributed string? i.e. the
"1"
is raised and compressed, whilst the
"12"
is lowered and also compressed.

thanks

Answer

If you want to have arbitrary fractions represented correctly, you should set the UIFontFeatureTypeIdentifierKey and UIFontFeatureSelectorIdentifierKey to kFractionsType and kDiagonalFractionsSelector respectively for UIFontDescriptorFeatureSettingsAttribute in a custom UIFontDescriptor. For example you can say something like:

let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 1000.0, height: 100.0))
let pointSize : CGFloat = 60.0
let systemFontDesc = UIFont.systemFontOfSize(pointSize,
    weight: UIFontWeightLight).fontDescriptor()
let fractionFontDesc = systemFontDesc.fontDescriptorByAddingAttributes(
    [
        UIFontDescriptorFeatureSettingsAttribute: [
            [
                UIFontFeatureTypeIdentifierKey: kFractionsType,
                UIFontFeatureSelectorIdentifierKey: kDiagonalFractionsSelector,
            ], ]
    ] )
label.font = UIFont(descriptor: fractionFontDesc, size:pointSize)
label.text = "The Fraction is: 23/271"

with the following result:

enter image description here

You can find more information here

Comments