在Swift中更改AttributedText的字体
我有一些在IB中创build的UILabel,这些UILabel都归因于文本。 每个标签的文本包含不同字体大小和颜色的多行。
在运行时,我希望能够改变这些标签的字体名称而不改变现有的字体大小或颜色。
我已经研究,找不到一个简单的方法来实现这一点。 有任何想法吗?
您首先需要了解苹果公司用来描述字体的术语:
-
Helvetica
是一个家庭 -
Helvetica Bold
,Helvetica Italic
,Helvetica Bold Italic
,Helvetica Display
等都是面孔 -
Helvetica Bold, 12pt
是一种字体
你想要的是replace属性string的字体系列 :
let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText) // Enumerate through all the font ranges newAttributedString.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, newAttributedString.length), options: []) { value, range, stop in guard let currentFont = value as? UIFont else { return } // An NSFontDescriptor describes the attributes of a font: family name, face name, point size, etc. // Here we describe the replacement font as coming from the "Hoefler Text" family let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptorFamilyAttribute: "Hoefler Text"]) // Ask the OS for an actual font that most closely matches the description above if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptorFamilyAttribute]).first { let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize) newAttributedString.addAttributes([NSFontAttributeName: newFont], range: range) } } label.attributedText = newAttributedString
原创(旧金山):
replace(Hoefler文本):
上面的工作很好,但与Swift4和Xcode 9.1我有一些警告方法名称已经改变。 以下是应用所有这些警告的结果。 否则我什么也没改。
let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText!) // Enumerate through all the font ranges newAttributedString.enumerateAttribute(NSAttributedStringKey.font, in: NSMakeRange(0, newAttributedString.length), options: []) { value, range, stop in guard let currentFont = value as? UIFont else { return } // An NSFontDescriptor describes the attributes of a font: family name, face name, point size, etc. // Here we describe the replacement font as coming from the "Hoefler Text" family let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptor.AttributeName.family: "Hoefler Text"]) // Ask the OS for an actual font that most closely matches the description above if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptor.AttributeName.family]).first { let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize) newAttributedString.addAttributes([NSAttributedStringKey.font: newFont], range: range) } } label.attributedText = newAttributedString