0

I'm trying to add a bold trait on an NSMutableAttributedString that may already be italics or underlined.

here is my current implementation which changes the whole font, thus losing the already existing traits.

    let text  = NSMutableAttributedString(attributedString: textView.attributedText)
    
    let normalFont = AppearanceManager.shared.font

    let boldFont = UIFont(descriptor: (normalFont?.fontDescriptor.withSymbolicTraits(.traitBold))!, size: normalFont?.pointSize ?? 14)

    //instead of adding .font, how do I just add a bold trait to the current font?
    text.addAttribute(.font, value: boldFont, range: textView.selectedRange)
    
    textView.attributedText = text
  • https://stackoverflow.com/questions/43723345/nsattributedstring-change-the-font-overall-but-keep-all-other-attributes ? – Larme Jul 13 '22 at 15:40
  • @Larme I actually am using the solution in that thread in my app as well. But it only lets you change the font while keeping the other attributes like(Bold/ Italics and underline). What I'm trying to achieve is to add a trait to an existing trait without replacing the font. If selected text is Helvetica 14 and Italics, I want to keep it as it is and just make it bold (making it **Helvetica** **14**, **Italics** and **Bold**) – Michael Sebsbe Jul 13 '22 at 15:58
  • 2
    It's a mix between your code to get the correct bold font, and enumerate all the fonts. You enumerate, when a font is found, get its bold equivalent, and apply it. – Larme Jul 13 '22 at 16:05
  • Thank you @Larme I modified the code to work – Michael Sebsbe Jul 13 '22 at 16:36

0 Answers0