i was wondering if there was a builtin method to represent
var someFraction = \"1/12\"
as an attributed string? i.e. the \"1\" is
Using the above UIFont extension:
static func fractionFont(forTextStyle textStyle: UIFontTextStyle) -> UIFont {
let font = UIFont.preferredFont(forTextStyle: .title1)
let descriptor = font.fontDescriptor.addingAttributes(
[
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kFractionsType,
UIFontDescriptor.FeatureKey.typeIdentifier: kDiagonalFractionsSelector,
],
]
] )
return UIFont(descriptor: descriptor, size: font.pointSize)
}
Then the following function somewhere:
func fractionMutableAttributedString(for string: String) -> NSMutableAttributedString {
let attributes: [NSAttributedStringKey: Any] = [.foregroundColor: UIColor.blue]
let attributedText = NSMutableAttributedString(string: string, attributes: attributes)
let substring = string.split(separator: " ") // Do we have a fractional value?
if substring[1].contains("/") {
let range = (string as NSString).range(of: String(substring[1]))
attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.fractionFont(forTextStyle: .title1), range: range)
}
return attributedText
}
and the use as:
let string = "3 5/6"
label.attributedText = fractionMutableAttributedString(for: string)
to produce the correct fraction.