ios - 在IOS运行时添加字体到textarea或webview?

标签 ios uiwebview fonts

我想在运行时向 IOS 应用程序添加自定义字体,并在可编辑文本区域或 contentEditable="on"的 UIWebView 中使用它。

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

这些替代方案是否可行:

  • 通过互联网下载字体并将其存储在应用文档文件夹中?
  • 使用 http 地址引用外部字体?
  • 通过 iTunes 传输字体?

iOS6 中的标签和富文本编辑有了很多改进,我希望自定义字体支持也能得到改进。

最佳答案

回答我自己的问题。

我还没有找到一种方法,可以在 iOS 中使用 native 文本区域执行此操作,而无需在 plist 文件中注册字体。

但是,UIWebView 确实支持@font-face 声明和.ttf 文件。诀窍是创建一个指向存储在 Documents 文件夹中的字体的 NSURL,然后使用 [webView stringByEvaluatingJavaScriptFromString] 告诉 Web View 使用它。

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

我的 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]];
}

在我的网页中:

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

关于ios - 在IOS运行时添加字体到textarea或webview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13013580/

相关文章:

iphone - UIWebView 更改 dataDetectorType 链接的颜色

swift - 设置自定义字体而不使用属性文本

css - JavaFx 8 - 在运行时更改 CSS 样式属性值

ios - 从另一个 VC 在第二个 VC 上加载 UIWebView

ios - iOS中HTML标签的字符串替换

ios - *.app 丢失,无法构建我的项目

ios - iAd 不显示任何广告、Swift、ViewController

html - 查看 Chromium 使用哪个字体文件来呈现文本 block

ios - 如何快速读取文档目录中的 json 文件?

ios - 链接 Storyboard引用时出现 ibtool 错误 : The file "Info.plist" couldn't be saved in the folder *. storyboardc