在Swift中只更改AttributedText的Font

Kas*_*hif 3 nsattributedstring uifont ios swift

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

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

我已经研究过,无法找到一种直接的方法来实现这一目标.有任何想法吗?

Cod*_*ent 10

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

  • Helvetica是一个家庭
  • Helvetica Bold,Helvetica Italic,Helvetica Bold Italic,Helvetica Display等是
  • Helvetica Bold, 12pt是一种字体

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

斯威夫特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
Run Code Online (Sandbox Code Playgroud)

斯威夫特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
Run Code Online (Sandbox Code Playgroud)

原件(旧金山):

旧金山

替换(Hoefler文本):

Hoefler文本


归档时间:

查看次数:

7559 次

最近记录:

7 年,3 月 前