Using custom font in a UIWebView
After some Try and Error I have found a reliable way to load custom Fonts with a local CSS.
1. Add your Font to the App...make sure that the file is targeted properly to the Application
2. Then add your Font to yourApp-Info.plist
3. Run NSLog(@"Available fonts: %@", [UIFont familyNames]);
To check which name the font/fontfamily has for the System...
4. Copy that name and use them in your CSS...@font-face is not needed
body { font-family:"Liberation Serif";}
I ended up making it work although I'm not sure what I did wrong above. Here's the HTML I use (NSString *htmll). I added everything, some of it might not be relevant for the solution.
<html><head><style type="text/css">@font-face {font-family: 'gotham_symbol';src: url('GOTHAMboldSymbols_0.ttf') format('truetype') }@font-face {font-family: 'gotham_symbol_italic';src: url('GothamBoldItalic.ttf') format('truetype') }#w {display:table;}#c {display:table-cell; vertical-align:middle;}i { font-family: 'Helvetica-BoldOblique'; }</style></head><body topmargin="0" leftmargin="0"><div style="display: table; width: 320px; height: 50px; #position: relative; overflow: hidden;"><div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;"><div style=" #position: relative; #top: -50%"><p style="font-size:20px;font-family:'gotham_symbol';color:#97371f;">THE TEXT GOES HERE</p></div></div></div></body></html>
and I load the UIWebView as follows:
UIWebView *webView = [[UIWebView alloc] initWithFrame:rect];[webView makeTransparent];NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];[webView loadHTMLString:html baseURL:baseURL];
For Swift and WKWebView, this worked for me:
@IBOutlet weak var webView: WKWebView!let html = """<!DOCTYPE html><head> <style> @font-face { font-family: 'Raleway-Regular'; src: url('Raleway-Regular.ttf') format('truetype') } img { width: 100%; } body { font-family: 'Raleway-Regular'; font-size: 30px; } </style></head><body> My HTML Content</body></html>"""let baseURL = URL(fileURLWithPath: Bundle.main.bundlePath)webView.loadHTMLString(html, baseURL: baseURL)
The fonts have to be added to the XCode project as you would normally do, and Copy bundle resources
<key>UIAppFonts</key><array> <string>Raleway-Bold.ttf</string> <string>Raleway-Regular.ttf</string></array>