我想知道是否有一个内置的方法来表示
var someFraction = "1/12"
作为属性字符串?即 “1”
被提升和压缩,而 “12”
被降低和压缩。
谢谢
最佳答案
如果您想正确表示任意分数,您应该将 UIFontFeatureTypeIdentifierKey
和 UIFontFeatureSelectorIdentifierKey
设置为 kFractionsType
和 kDiagonalFractionsSelector
分别用于自定义 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"
结果如下:
您可以找到更多信息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()
关于swift - 有没有一种巧妙的方法可以将分数表示为属性字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883994/