I have some UIFont
s like this:
let regularFont = UIFont.systemFont(ofSize: 18, weight: .regular)
let mediumFont = UIFont.systemFont(ofSize: 18, weight: .medium)
I use them in my UIKit components like UILabel
.
Now I want to render some text in a WKWebView using the same fonts.
I generate some html template in code but I can't figure out how to setup the css font styles to match my given UIFonts.
With some guesswork I came up with the following which kind of works for my given examples:
<html>
<head>
<style>
body {
font-family: '.AppleSystemUIFont';
font-size: 18.0;
font-weight: normal;
}
b {
font-family: '.AppleSystemUIFont';
font-size: 18.0;
font-weight: bolder;
}
</style>
</head>
<body>
<p>
Regular font <b>Medium font</b> Regular font
</p>
</body>
</html>
It works ok-ish but clearly this does not scale (how about other weights?).
Also I can already see my designer coming at me, claiming that font weight is off by .1 or something.
This is my current effort. It works on a limited subset of properties (bold, italic) but it does not handle font weight. Also I haven't tested for custom fonts yet but my guess is it won't work like that.
extension UIFont {
func cssStyleString(color: UIColor) -> String {
let colorString = "rgb( \(CIColor(color: color).red * 255), \(CIColor(color: color).green * 255), \(CIColor(color: color).blue * 255) )"
// not sure this is right
let fontFamily = self.fontName == self.familyName
let fontSize = self.pointSize
// trait is not quite right for translation into weight. suggestions?
let fontWeight = self.fontDescriptor.symbolicTraits.contains(.traitBold) ? "bold" : "normal"
// works for italic only.
let fontStyle = self.fontDescriptor.symbolicTraits.contains(.traitItalic) ? "italic" : "normal"
return "font-family: '\(fontFamily)'; font-size: \(fontSize); font-weight: \(fontWeight); font-style: \(fontStyle); color: \(colorString); "
}
}
So hence my question:
What is the best way to create css styles from a given UIFont, especially with respect to font weight?