我想知道是否有内置方法来表示
var someFraction = "1/12"
Run Code Online (Sandbox Code Playgroud)
作为属性字符串?即"1"升高和压缩,同时"12"降低并压缩.
谢谢
如果你想拥有任意分数正确表示,应设置UIFontFeatureTypeIdentifierKey并UIFontFeatureSelectorIdentifierKey以kFractionsType和kDiagonalFractionsSelector分别为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)
结果如下:
您可以在此处找到更多信息
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)
| 归档时间: |
|
| 查看次数: |
783 次 |
| 最近记录: |