I use this code to convert a description with HTML Markup into a 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
}
It works well for the font "Helvetica Neue" in iOS8, because the HTML markup I happen to be working with is very basic and doesn't contain any special fonts or links, etc.
Unfortunately, the font name "San Francisco" doesn't work on iOS 9 beta 5, it just uses the default Times New Roman font.
How can I create an attributedString from a description in iOS 9 using the San Francisco Font?
Edit 1:
I've tried replacing better description with
let betterDescription = "<html><head><style type=\"text/css\"> body { font-family: -apple-system; } </style></head><body>" + description + "</body></html>"
but that didn't seem to help either...
Using this code to log the fonts on iOS 9 reveals that you can use .SF UI Text
in order to get the new San Francisco font and then you can apply it to your attributed string as well.
let fontFamily = UIFont.systemFontOfSize(UIFont.systemFontSize()).familyName
print(fontFamily)
if let attributedString = attributedStringFromDescription(originalDescription, withFontName: fontFamily) {
myLabel.attributedText = attributedString
}