Fonts added at runtime in IOS to textarea or webview?-Collection of common programming errors

Answering my own question.

I have not found a way to do this with a native textarea in iOS without registering the font in the plist file.

How ever, the UIWebView does support @font-face declarations and .ttf files. The trick is to create a NSURL that points to the font stored in the Documents folder and then tell the web view to use this by using [webView stringByEvaluatingJavaScriptFromString].

In my first tests I did something like this:

My view controller:

- (NSString *)documentsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

- (void) setFont {
    NSString *urlPath = [[self documentsDirectory]
                         stringByAppendingPathComponent:@"myfont.ttf"];
    NSURL *url = [NSURL fileURLWithPath:urlPath];
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setFont('%@');", url]];
}

In my web page:

       
    body {
        font-family: customfont;
        font-size: 40px;
    }        


    function setFont(font) {
        var id = 'customfont',
            head = document.getElementsByTagName("head")[0],
        style;

        style = document.getElementById(id);
        if(style) {
            head.removeChild(style);
        }

        style = document.createElement("style");
        style.setAttribute("id", id);
        style.textContent = "@font-face { font-family: '" + id + "'; src: url('" + font + "'); font-weight: normal; font-style: normal; }"
        head.appendChild(style);
    }