Search code examples
swiftfractions

How to display fraction text number over another?


I need to display a fraction in my app but cannot find a good way to do it?

Should looks something like this

enter image description here(proof of concept... don't need the font):

There is other posts similar to this but they are in ObJ C, I can not find a reliable solution in swift


Solution

  • This is just Apple sample code from the Introducing the New System Fonts video from WWDC 2015 put into a playground and using a UILabel to render plain text fractions using font features. [Updated for Swift 4]

    //: Playground - noun: a place where people can play
    
    import UIKit
    import CoreGraphics
    
    let pointSize : CGFloat = 60.0
    let systemFontDesc = UIFont.systemFont(ofSize: pointSize,
                                           weight: UIFont.Weight.light).fontDescriptor
    let fractionFontDesc = systemFontDesc.addingAttributes(
        [
            UIFontDescriptor.AttributeName.featureSettings: [
                [
                    UIFontDescriptor.FeatureKey.featureIdentifier: kFractionsType,
                    UIFontDescriptor.FeatureKey.typeIdentifier: kDiagonalFractionsSelector,
                    ],
            ]
        ] )
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
    
    label.font = UIFont(descriptor: fractionFontDesc, size:pointSize)
    label.text = "12/48" // note just plain numbers and a regular slash
    

    Just tap on the eye in the playground and you will see a beautiful fraction.

    Introducing the New System Fonts (WWDC 2015 at 20:24)