swift - 有没有一种巧妙的方法可以将分数表示为属性字符串?

标签 swift

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

var someFraction = "1/12"

作为属性字符串?即 “1” 被提升和压缩,而 “12” 被降低和压缩。

谢谢

最佳答案

如果您想正确表示任意分数,您应该将 UIFontFeatureTypeIdentifierKeyUIFontFeatureSelectorIdentifierKey 设置为 kFractionsTypekDiagonalFractionsSelector 分别用于自定义 UIFontDescriptor 中的 UIFontDescriptorFeatureSettingsAttribute。例如你可以这样说:

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"

结果如下:

enter image description here

您可以找到更多信息here

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()

enter image description here

关于swift - 有没有一种巧妙的方法可以将分数表示为属性字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883994/

相关文章:

ios - 从一种模态 VC 到另一种模态 VC 的快速过渡

ios - 在哪里放置用户登录与用户注销逻辑?

ios - 禁用编辑但允许继续快速输入

ios - Swift:使用 NSOperation 保留循环

ios - 自定义View ui元素显示

ios - 递归调用闭包

swift - 下载 Alamofire 时应用卡住

ios - 从 Cognito 向客户端发布身份验证自定义响应

ios - avplayer seek 在音频文件中播放错误的位置

ios - 有效地检查核心数据中是否存在项目