0

I've got the following extension to turn an API response in html format into a NSAttributedString, styled with CSS:

extension String {
public func convertHtmlToAttributedStringWithCSS(bodyFont: UIFont, h1Font: UIFont, csscolor: String, lineheight: Int, csstextalign: String) -> NSAttributedString? {
        let modifiedString =
        "<style>" +
            "body{" +
                "font-family: '\(bodyFont.fontName)'; " +
                "font-size:\(bodyFont.pointSize)px; " +
                "color: \(csscolor); " +
                "line-height: \(lineheight)px; " +
                "text-align: \(csstextalign); " +
            "} " +
            "h1{" +
                "font-family: '\(h1Font.fontName)'; " +
                "font-size:\(h1Font.pointSize)px; " +
            "}" +
        "</style>\(self)";
        guard let data = modifiedString.data(using: .utf8) else {
            return nil
        }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }
        catch {
            print(error)
            return nil
        }
    }
}

I'm calling it like so:

self.CampaignDescriptionBody.attributedText = briefing!.convertHtmlToAttributedStringWithCSS(bodyFont: UIFont.systemFont(ofSize: 12), h1Font: UIFont.systemFont(ofSize: 15), csscolor: "grey", lineheight: 5, csstextalign: "left")

Fontsize, textalignment, etc works fine. My issue is, that the font on screen does not at all look like the System Font, which seems to be San Francisco now.

Here's a screenshot of 2 UILabels that sit next to each other on screen. "Campaign Description" is set to "System Bold 15" in the Interface Builder "Exklusivität" is a piece of the API response that is turned into an NSAttributedString, so it should render with the same font but obviously doesn't.

enter image description here

Does anyone know what I'm doing wrong here?

3
  • Try with font-family: '-apple-system'. Commented Feb 24, 2020 at 17:06
  • @Gereon: Bingo - thanks!! Commented Feb 24, 2020 at 17:14
  • OK great :) - I wasn't 100% percent sure. I'm going to add this as an answer then. Commented Feb 24, 2020 at 17:16

1 Answer 1

1

To get the San Francisco font via CSS, use font-family: '-apple-system'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.