在iOS的运行时添加了字体,以添加到TextArea或WebView



我想将运行时的自定义字体添加到iOS应用程序中,并在可编辑的textarea或带有contineDeaditable =" on"的uiwebview中使用它。

我知道您是如何在编译时捆绑自定义字体的,但是我需要在运行时执行此操作。

是可能的任何替代方法:

  • 通过Internet下载字体并存储在应用程序文件夹中?
  • 使用HTTP地址的参考外部字体?
  • 通过iTunes传输字体?

在ios6中,标签和丰富的文本编辑有了很多改进,我希望自定义字体支持也有所改善。

回答我自己的问题。

我尚未找到一种在iOS中使用本机Textarea执行此操作的方法,而无需在PLIST文件中注册字体。

,UIWebView确实支持 @font-face声明和.ttf文件。诀窍是创建一个指向文档文件夹中存储的字体的NSURL,然后告诉Web视图通过使用[WebView StringByEvaluationjavascriptFromstring]。

在我的第一次测试中,我做了这样的事情:

我的视图控制器:

- (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]];
}

在我的网页中:

<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>

最新更新