-1

this questions follows on from Is there a neat way to represent a fraction as an attributed string?.

i have a function that provides a font for a fraction string

func fractionFont() -> UIFont {
    let pointSize = CGFloat(20.0)
    let systemFontDescriptor = UIFont.systemFontOfSize(pointSize, weight: UIFontWeightLight).fontDescriptor()
    let fractionFontDescriptor = systemFontDescriptor.fontDescriptorByAddingAttributes(
    [
        UIFontDescriptorFeatureSettingsAttribute: [
        [
            UIFontFeatureTypeIdentifierKey: kFractionsType,
            UIFontFeatureSelectorIdentifierKey: kDiagonalFractionsSelector,
        ], ]
    ] )
    return UIFont(descriptor: fractionFontDescriptor, size: pointSize)
}

and i use in it for a label property in SomeClass

class SomeClass {
    @IBOutlet weak var fractionLabel: UILabel! {
        didSet {
            fractionLabel.text = "1/2"
            fractionLabel.font = fractionFont()
        }
    }
}

say i want to use fractionFont method again in AnotherClass i guess copying the code is not a great idea. i was also advised in another post to use so called Singleton classes sparingly, so what's the best approach for this?

  • thanks
Community
  • 1
  • 1
ajrlewis
  • 2,968
  • 3
  • 33
  • 67

2 Answers2

5

I'd extend UIFont with your fractionFont method:

extension UIFont {
    class func fractionFont() -> UIFont {
        /* Code here */
    }
}
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 2
    Best part about this is that Swift will let you reference the class method without the class name if the type is inferred. `fractionLabel.font = .fractionFont()` – Nate Cook Feb 12 '16 at 18:57
  • @mipadi great - whats the practice for adding these extensions - in a dedicated .swift file? – ajrlewis Feb 12 '16 at 18:57
  • 1
    @Alex: If there's another file it makes sense it (maybe something dealing with fonts or other UI details) I'd put it there. Otherwise, a separate file would be fine. – mipadi Feb 12 '16 at 19:06
  • @mipadi thanks - made an "Extensions.swift" and it worked a treat following advice from NateCook. – ajrlewis Feb 12 '16 at 19:14
0

Create a class like Misc Paste your function as class func in there. Now you can call it like this fractionLabel.font = Misc.fractionFont()

smnk
  • 471
  • 1
  • 6
  • 25