Friday, November 25, 2011

Applying Java script to UIWebView from Objective C - iPhone SDK

//------------------------------------------------------------------------------------------------------------ 
/*Java script code */
function switchFontsize(val)
{
    if(val)
    {
         document.getElementById("myDivId").style.fontSize = val + "px";
         document.getElementById("mySecondDivId").style.fontSize = val + "px";
    }
}
//-------------------------------------------------------------------------------------------------------------
/* Objective C function to apply font to the web view */
+ (void)applyFontToWebView:(UIWebView *)webView withFontSize:(int)fontSize
{
    NSString *jsString = [NSString stringWithFormat:@"switchFontsize(%d)",fontSize];
    [webView stringByEvaluatingJavaScriptFromString:jsString];
}
//-------------------------------------------------------------------------------------------------------------
/* Function to call when font plus button press event */
- (void)increaseFont
{
    // 24 is set as the maximum font size.
    if (currentFontSize < 24)
    {
        currentFontSize = currentFontSize + 2;
    }
    [FontClass applyFontToWebView:self.webView withFontSize:currentFontSize];
}

Note - Make sure that you are calling the java script file in the html string loaded in the webview.

No comments:

Post a Comment