使用 Swift 将带有 HTML 标记的描述转换为 iOS 上的 NSAttributedString 时如何使用旧金山字体

How to use San Francisco Font when converting a description with HTML Markup to NSAttributedString on iOS using Swift

我使用此代码将带有 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 中的描述创建 attributedString?

编辑 1:

我尝试用

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

但这似乎也无济于事...

使用此代码在 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
    }