Search code examples
iosswiftlocalizationnsattributedstringlocalizable.strings

iOS - Emphasise with bold strings in Localizable.strings


Is there a way bold some words inside the Localizable file like so?

"Pending network connection" = "<b>Pending</b> network connection";

I have this string inside and i want to emphasis only certen words:

 "camSave" = "To complete onboarding:\n1. Tap Save and disconnect to disconnect from the camera.\n2. Connect to the internet.\n3. Log in to Cloud.";

Btw i want to use it inside alert


Solution

  • You can actually use HTML tags with NSAttributedString. This is what I used:

    static func convertFromHTMLString(_ input: String?) -> NSAttributedString? {
        guard let input = input else { return nil }
    
        guard let data = input.data(using: String.Encoding.unicode, allowLossyConversion: true) else { return nil  }
        return try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
    }
    

    So I convert an input string to raw data using UTF8 format. Then I use a constructor of attributed string with data using appropriate flags NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html.