Johan Nordberg
Johan Nordberg

Reputation: 3777

Fonts added at runtime in IOS to textarea or webview?

I'd like to add custom fonts at runtime to an IOS app and use it in either a editable textarea or a UIWebView with contentEditable="on".

I know how you bundle custom fonts at compile time, but I need to do this at runtime.

Is any of these alternatives possible:

There's been lot's of improvements to labels and rich text editing in iOS6, and I was hoping that custom font support has improved as well.

Upvotes: 0

Views: 394

Answers (1)

Johan Nordberg
Johan Nordberg

Reputation: 3777

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:

<style>       
    body {
        font-family: customfont;
        font-size: 40px;
    }        
</style>
<script>
    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);
    }
</script>

Upvotes: 1

Related Questions