2017-02-18 31 views
2

У меня есть несколько UILabels, созданных в IB, которые все приписали текст. Текст каждого ярлыка содержит несколько строк разных размеров и цветов шрифта.Изменить только шрифт AttributedText в Swift

Во время выполнения я хочу иметь возможность изменять только имя шрифта этих меток без изменения существующих размеров шрифтов или цветов.

Я исследовал и не смог найти прямой метод для достижения этого. Есть идеи?

+0

Возможный дубликат [ИОС скоро: Можно ли изменить стиль шрифта определенного слова в строке] (http://stackoverflow.com/questions/29165560/ios-swift-is-it -possible-to-change-the-font-style-of-a-some-word-in-a-string) –

+0

и http://stackoverflow.com/questions/18365631/example-of-nsattributedstring-with-two -different-font-size –

+0

@Sneak: Эти вопросы/ответы, похоже, не затрагивают основную проблему, оставляя исходные атрибуты неизменными, как цвет шрифта, размер шрифта и т. д. – Kashif

ответ

6

Сначала необходимо понять жаргон 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 (Сан-Франциско):

San Francisco

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

Hoefler Text

-1

Вышеупомянутые работы замечательные, но с 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 

 Смежные вопросы

  • Нет связанных вопросов^_^