在 iOS 上使用 Swift 将带有 HTML 标记的描述转换为 NSAttributedString 时如何使用 San Francisco 字体

问题描述 投票:0回答:2

我使用此代码将带有 HTML 标记的描述转换为 NSAttributedString。

func attributedStringFromDescription(description: String, withFontName fontName: String) -> NSAttributedString? {
    let attributedOptions : [String: AnyObject] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding]
    let betterDescription = "<br><font face=\"\(fontName)\">" + description + "</font>"
    if let encodedData = betterDescription.dataUsingEncoding(NSUTF8StringEncoding) {
        return NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)
    }
    return nil
}

它适用于 iOS8 中的字体“Helvetica Neue”,因为我碰巧使用的 HTML 标记非常基本,不包含任何特殊字体或链接等。

不幸的是,字体名称“San Francisco”在 iOS 9 beta 5 上不起作用,它只是使用默认的 Times New Roman 字体。

如何使用 San Francisco 字体从 iOS 9 中的描述创建属性字符串?

编辑1:

我尝试用

替换更好的描述
let betterDescription = "<html><head><style type=\"text/css\"> body { font-family: -apple-system; } </style></head><body>" + description + "</body></html>"

但这似乎也没有帮助......

html ios swift fonts nsattributedstring
2个回答
2
投票

使用此代码在 iOS 9 上记录字体表明您可以使用

.SF UI Text
来获取新的 San Francisco 字体,然后您也可以将其应用到您的属性字符串。

    let fontFamily = UIFont.systemFontOfSize(UIFont.systemFontSize()).familyName
    print(fontFamily)

    if let attributedString = attributedStringFromDescription(originalDescription, withFontName: fontFamily) {
        myLabel.attributedText = attributedString
    }

0
投票

顺便说一句:原来的问题显示该功能已过时。对于较新版本的 swift,这是可行的:

    func attributedStringFromHtml(_ description: String, withFontName fontName: String) -> NSAttributedString? {
        let htmlString = "<span style=\"font-family: '\(fontName)';\">\(description)</span>"
        guard let data = htmlString.data(using: .utf8) else { return nil }

        // Options for the attributed string
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]

        do {
            // Attempt to create an attributed string
            let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil)
            return attributedString
        } catch {
            print("Error creating attributed string from HTML: \(error)")
            return nil
        }
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.