Сначала необходимо понять жаргон Apple, использует для описания шрифта:
Helvetica
является семья
Helvetica Bold
, Helvetica Italic
, Helvetica Bold Italic
, Helvetica Display
т.д. лица
Helvetica Bold, 12pt
является font
Что вы хотите, чтобы заменить семью шрифта в качестве приписываемой строки:
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
Original (Сан-Франциско):

Замена (Hoefler Текст):

Возможный дубликат [ИОС скоро: Можно ли изменить стиль шрифта определенного слова в строке] (http://stackoverflow.com/questions/29165560/ios-swift-is-it -possible-to-change-the-font-style-of-a-some-word-in-a-string) –
и http://stackoverflow.com/questions/18365631/example-of-nsattributedstring-with-two -different-font-size –
@Sneak: Эти вопросы/ответы, похоже, не затрагивают основную проблему, оставляя исходные атрибуты неизменными, как цвет шрифта, размер шрифта и т. д. – Kashif