Question

I have a javascript method to pass in to stringByEvaluatingJavaScriptFromString: in a UIWebView subclass.

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

I've added it to the stringByEvaluatingJavaScriptFromString: method and as long as I specify a pixel value, the code works. If I use a variable like the code below, it doesn't do anything. What am I doing wrong?

I'm using the largerBool to tell me if the spacing needs to increase or decrease. Then I'm setting max and min, and using line height as the variable.

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

I'm also using the didFinishLoading delegate method of UIWebView to save the current line spacing value.

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

All I get is '0' in the Log.

Thanks in advance!

No correct solution

OTHER TIPS

First, line-height: '%d%%'px should be line-height: '%d'px. Otherwise, you will build something like line-height: '12%%'px, which won't be parsed when the source is rendered.


Second, stringValue will be something like "12px", so you cannot directly convert it to a number without removing "px".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top