UIWebView 更改源中文本的行距

UIWebView change line spacing for text in source

本文关键字:文本 中文 UIWebView      更新时间:2023-09-26

我有一个javascript方法可以传递给stringByEvaluatingJavaScriptFromString:在UIWebView子类中。

var head = document.getElementsByTagName('head')[0],
    style = document.createElement('style'),
    rules = document.createTextNode('* { line-height: 20px !important; }');
style.type = 'text/css';
if(style.styleSheet)
    style.styleSheet.cssText = rules.nodeValue;
else style.appendChild(rules);
head.appendChild(style);

我已将其添加到stringByEvaluatingJavaScriptFromString:方法中,只要我指定像素值,代码就可以工作。如果我使用类似于以下代码的变量,它不会执行任何操作。我做错了什么?

我正在使用更大的布尔值来告诉我间距是否需要增加或减少。然后我设置 max 和 min,并使用行高作为变量。

   - (void)changeLineSpacingLarger:(BOOL)largerBool {
    if (largerBool == YES) { // A+
        lineHeight = (lineHeight < 100) ? lineHeight +10 : lineHeight;
    }
    else if (largerBool == NO) { // A-
        lineHeight = (lineHeight > 20) ? lineHeight -10 : lineHeight;
    }
    NSString *jsString = [[NSString alloc] initWithFormat:@"var head = document.getElementsByTagName('head')[0], style = document.createElement('style'), rules = document.createTextNode('* { line-height: '%d%%'px !important; }'); style.type = 'text/css'; if(style.styleSheet) style.styleSheet.cssText = rules.nodeValue; else style.appendChild(rules); head.appendChild(style);", lineHeight];
    [self stringByEvaluatingJavaScriptFromString:jsString];
}

我还使用 UIWebView 的 didFinishLoading 委托方法来保存当前的行距值。

- (void)updateLineSpacingValue {
    NSString *jsString = [[NSString alloc] initWithFormat:@"var element = document.getElementsByTagName('h1')[0], style = window.getComputedStyle(element), lh = style.getPropertyValue('line-height'); return lh;", textFontSize];
    NSString *stringValue = [self stringByEvaluatingJavaScriptFromString:jsString];
    lineHeight = [stringValue intValue];
    NSLog(@"Line Height: %i", lineHeight);
}

我得到的只是日志中的"0"。

提前感谢!

首先,line-height: '%d%%'px应该是line-height: '%d'px的。否则,您将构建类似 line-height: '12%%'px 的东西,在渲染源时不会对其进行解析。


其次,stringValue将是类似于"12px"的东西,因此如果不删除"px",则无法将其直接转换为数字。