我想知道是否有内置方法来表示
var someFraction = "1/12"
作为属性字符串?即"1"
被抬起并压缩,而"12"
被降低并被压缩。
感谢
答案 0 :(得分:6)
如果要正确表示任意分数,则应分别为自定义UIFontDescriptor中的UIFontDescriptorFeatureSettingsAttribute设置org.hibernate.spatial.dialect.oracle.OracleSpatial10gDialect.properties
和UIFontFeatureTypeIdentifierKey
为UIFontFeatureSelectorIdentifierKey
和kFractionsType
。例如,你可以这样说:
kDiagonalFractionsSelector
具有以下结果:
您可以找到更多信息here
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"
答案 1 :(得分:1)
您可以使用unicode显示分数而不是使用归因字符串。这个link有一个用目标C编写的源代码。您可以轻松地将其移植到swift中。
答案 2 :(得分:0)
使用上面的UIFont
扩展名:
static func fractionFont(forTextStyle textStyle: UIFontTextStyle) -> UIFont {
let font = UIFont.preferredFont(forTextStyle: .title1)
let descriptor = font.fontDescriptor.addingAttributes(
[
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kFractionsType,
UIFontDescriptor.FeatureKey.typeIdentifier: kDiagonalFractionsSelector,
],
]
] )
return UIFont(descriptor: descriptor, size: font.pointSize)
}
然后在某处添加以下功能:
func fractionMutableAttributedString(for string: String) -> NSMutableAttributedString {
let attributes: [NSAttributedStringKey: Any] = [.foregroundColor: UIColor.blue]
let attributedText = NSMutableAttributedString(string: string, attributes: attributes)
let substring = string.split(separator: " ") // Do we have a fractional value?
if substring[1].contains("/") {
let range = (string as NSString).range(of: String(substring[1]))
attributedText.addAttribute(NSAttributedStringKey.font, value: UIFont.fractionFont(forTextStyle: .title1), range: range)
}
return attributedText
}
及其用途:
let string = "3 5/6"
label.attributedText = fractionMutableAttributedString(for: string)
产生正确的分数。