gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:53:44 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com