是否有一种巧妙的方法将分数表示为属性字符串?

ale*_*wis 1 swift

我想知道是否有内置方法来表示

var someFraction = "1/12"
Run Code Online (Sandbox Code Playgroud)

作为属性字符串?即"1"升高和压缩,同时"12"降低并压缩.

谢谢

bey*_*ulf 6

如果你想拥有任意分数正确表示,应设置UIFontFeatureTypeIdentifierKeyUIFontFeatureSelectorIdentifierKeykFractionsTypekDiagonalFractionsSelector分别为UIFontDescriptorFeatureSettingsAttribute在自定义UIFontDescriptor.例如,你可以这样说:

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"
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

您可以在此处找到更多信息

Swift 3.0

extension UIFont
{
    static func fractionFont(ofSize pointSize: CGFloat) -> UIFont
    {
        let systemFontDesc = UIFont.systemFont(ofSize: pointSize).fontDescriptor
        let fractionFontDesc = systemFontDesc.addingAttributes(
            [
                UIFontDescriptorFeatureSettingsAttribute: [
                    [
                        UIFontFeatureTypeIdentifierKey: kFractionsType,
                        UIFontFeatureSelectorIdentifierKey: kDiagonalFractionsSelector,
                    ], ]
            ] )
        return UIFont(descriptor: fractionFontDesc, size:pointSize)
    }
}

let label = UILabel()
label.backgroundColor = .white
let pointSize: CGFloat = 45.0
let string = "This is a mixed fraction 312/13"
let attribString = NSMutableAttributedString(string: string, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: pointSize), NSForegroundColorAttributeName: UIColor.black])
attribString.addAttributes([NSFontAttributeName: UIFont.fractionFont(ofSize: pointSize)], range: (string as NSString).range(of: "12/13"))
label.attributedText = attribString
label.sizeToFit()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述