变化斯威夫特
问题描述:
AttributedText的只是字体我有一些在IB创建UILabels这一切都已归于文本。每个标签的文本都包含多行不同字体大小和颜色。变化斯威夫特
在运行时,我希望能够在不更改现有字体大小或颜色的情况下更改这些标签的字体名称。
我已经研究过,无法找到一个简单的方法来实现这一点。有任何想法吗?
答
你首先需要了解苹果公司用来描述字体的行话
-
Helvetica
是家庭 -
Helvetica Bold
,Helvetica Italic
,Helvetica Bold Italic
,Helvetica Display
等都是面临 -
Helvetica Bold, 12pt
是一个字体
你需要的是更换一个属性串的字体家族:
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
原件(旧金山):
更换(Hoefler文本):
答
以上的伟大工程,但与Swift4和9.1的Xcode我得到这个方法的名字改变了警告的数量。以下是应用所有这些警告的结果。否则,我没有改变任何东西。
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
的可能的复制[IOS SWIFT:是否有可能改变某个词的字体样式的字符串(http://*.com/questions/29165560/ios-swift-is-it - 可以改变某种字符串的字体风格) – 2017-02-18 17:02:43
和http://*.com/questions/18365631/example-of-nsattributedstring-with-two -different-font-sizes – 2017-02-18 17:03:01
@Sneak:这些问题似乎没有解决保留原始属性如字体颜色,字体大小等的核心问题。 – Kashif