Search code examples
htmliosswiftwatchkitwatchos-2

".SFUIText-Regular" doesn't exist on watchOS


I am creating an app for Apple Watch and iOS. I have HTML data which I transform into NSAttributedString to display in a UITextView (on iOS). I also want to send it to the watch to display it in a label.

Everything looks ok in the text view (e.g., correct background color). On the watch, it only displays the text (without any colors) and returns this error:

app-Watch Extension[2994:212335] CoreText: PostScript name ".SFUIText-Regular" does not exist.

Here is my code:

let mutAttText = NSMutableAttributedString(attributedString: self.textView.attributedText)
let attributedOptions : [String: AnyObject] = [
    NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
    NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
var data: NSData = NSData()
do {
data = try mutAttText.dataFromRange(NSMakeRange(0, mutAttText.length), documentAttributes: attributedOptions)
} catch {

}


let htmlString = NSString(data: data, encoding: NSUTF8StringEncoding)
print(htmlString)

var attrStr = NSMutableAttributedString()
do {
    attrStr = try NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType], documentAttributes: nil)
    attrStr.enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, attrStr.length), options: NSAttributedStringEnumerationOptions.LongestEffectiveRangeNotRequired, usingBlock: { (attribute: AnyObject?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
        if let attributeFont = attribute as? UIFont {
            let newPointSize = CGFloat(15)
            let scaledFont = UIFont(descriptor: attributeFont.fontDescriptor(), size: newPointSize)
            attrStr.addAttribute(NSFontAttributeName, value: scaledFont, range: range)
        }
    })
    self.textView.attributedText = attrStr
    self.sendText(attrStr)
}
catch {
    print("error creating attributed string")
}

Solution

  • Although iOS and watchOS both use the San Francisco font, the fonts do differ between platforms:

    • iOS, tvOS, and OS X uses San Francisco (SF-UI).

    • watchOS uses San Francisco Compact (SF-Compact).

    It looks like you're trying to scale the pointSize of an iOS system font, but .SFUIText-Regular doesn't exist on watchOS.

    You also may want to use systemFontOfSize: instead of trying to scale the point size of a named font, since there are different (text and display) versions depending on point size. This will allow the system to automatically select the appropriate (text or display) variant for that point size.