iOS增加UIWebView字体大小

时间:2014-04-22 14:45:48

标签: ios uiwebview

我在Stack Overflow上寻找解决方案,但我找不到。我的代码是:

CGRect  rect = _postContentView.bounds;
_postContentUIWV = [[UIWebView alloc] initWithFrame:rect];
[_postContentUIWV loadHTMLString:selectedPostCD.content baseURL:nil];

int fontSize = 30;
NSString *jsString = [[NSString alloc] initWithFormat:
    @"document.getElementsByTagName('span')[0].style.webkitTextSizeAdjust='%d%%'",
    fontSize];
[_postContentUIWV stringByEvaluatingJavaScriptFromString:jsString];

[_postContentView addSubview:_postContentUIWV];

HTML UIWebView中的部分内容:

<p style="text-align: justify;">
    <span style="line-height: 1.5em;">blablablablablabla</span>
</p>

我的代码不会增加UIWebView内的字体大小。我该如何解决?

3 个答案:

答案 0 :(得分:4)

_postContentUIWV方法中保留与viewDidLoad的创建和初始化相关的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect  rect = _postContentView.bounds;
    _postContentUIWV = [[UIWebView alloc] initWithFrame:rect];
    _postContentUIWV.delegate = self;
    [_postContentUIWV loadHTMLString:selectedPostCD.content baseURL:nil];
    [_postContentView addSubview:_postContentUIWV];
}

将与jsString评估相关的代码移至webViewDidFinishLoad方法:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    int fontSize = 30;
    NSString *jsString = [[NSString alloc] initWithFormat:
        @"document.getElementsByTagName('span')[0].style.webkitTextSizeAdjust='%d%%'",
        fontSize];
    [_postContentUIWV stringByEvaluatingJavaScriptFromString:jsString];
}

答案 1 :(得分:1)

此外,您可以将字符串连接到UIWebView

中的现有HTML
NSString * htmlString = @"<style>p {font-size:28px}</style>";
makeBiggerCssString = [makeBiggerCssString stringByAppendingString:
                       selectedPostCD.content];
[_postContentUIWV loadHTMLString: htmlString baseURL:nil];

答案 2 :(得分:1)

试试这个方法:

NSString *htmlString =[NSString stringWithFormat:@"<font face='Font_name' size='30'>%@", Yourstring];
[webview loadHTMLString:htmlString baseURL:nil];