在Swift中只更改AttributedText的Font

时间:2017-02-18 17:00:11

标签: ios swift nsattributedstring uifont

我在IB中创建了许多UILabel,这些UILabel都归因于文本。每个标签的文本包含多行不同的字体大小和颜色。

在运行时,我希望能够只更改这些标签的字体名称,而无需更改现有的字体大小或颜色。

我已经研究过,无法找到实现这一目标的直接方法。有什么想法吗?

2 个答案:

答案 0 :(得分:9)

首先,您需要了解Apple用于描述字体的术语:

  • Helvetica系列
  • Helvetica BoldHelvetica ItalicHelvetica Bold ItalicHelvetica Display faces
  • Helvetica Bold, 12pt font

您想要的是替换属性字符串的字体系列

Swift 4

// Enumerate through all the font ranges
newAttributedString.enumerateAttribute(.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([.family: "Hoefler Text"])

    // Ask the OS for an actual font that most closely matches the description above
    if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [.family]).first {
        let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize)
        newAttributedString.addAttributes([.font: newFont], range: range)
    }
}

label.attributedText = newAttributedString

Swift 3

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 Text):

Hoefler Text

答案 1 :(得分:1)

以上工作很好但是使用Swift4和Xcode 9.1我得到了一些警告,方法名称已经改变了。以下是应用所有这些警告的结果。否则我没有改变任何东西。

chmod -R 777