2
votes

I'm using a meta viewport as mentioned here Why does UIWebView shrink images? for UIWebView. This formats portrait fine and I don't have to compensate for weird scaling. However, once rotated to landscape, I can't take advantage of the additional width. Meaning, I'd like to fit more text into a single line for landscape. Everything keeps scaled at 1.0. Is there a way to change viewport to .75 scaling on rotation and back to 1.0 in portrait?

1

1 Answers

0
votes

I wrote this function to set the viewport width as a UIWebView is resized. You can easily adapt it to set a viewport property other than width.

-(NSString *) setViewportWidth:(CGFloat)inWidth {
    NSString *result = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"(function ( inWidth ) { "
        "var result = ''; "
        "var viewport = null; "
        "var content = 'width = ' + inWidth; "
        "var document_head = document.getElementsByTagName('head')[0]; "
        "var child = document_head.firstChild; "
        "while ( child ) { "
            "if ( null == viewport && child.nodeType == 1 && child.nodeName == 'META' && child.getAttribute( 'name' ) == 'viewport' ) { "
                "viewport = child; "
                "content = child.getAttribute( 'content' ); "
                "if ( content.search( /width\\s=\\s[^,]+/ ) < 0 ) { "
                    "content = 'width = ' + inWidth + ', ' + content; "
                "} else { "
                    "content = content.replace( /width\\s=\\s[^,]+/ , 'width = ' + inWidth ); "
                "} "
            "} "
            "child = child.nextSibling; "
        "} "
        "if ( null != content ) { "
            "child = document.createElement( 'meta' ); "
            "child.setAttribute( 'name' , 'viewport' ); "
            "child.setAttribute( 'content' , content ); "
            "if ( null == viewport ) { "
                "document_head.appendChild( child ); "
                "result = 'append viewport ' + content; "
            "} else { "
                "document_head.replaceChild( child , viewport ); "
                "result = 'replace viewport ' + content; "
            "} "
        "} "
        "return result; "
    "})( %d )" , (int)inWidth]];

    return result;
}