您的位置:首页 > 移动开发

关于UIWebView的一些常用属性和用法汇总

2014-12-10 14:09 495 查看
1、UIWebView设置字体大小,颜色,字体:

UIWebView无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置,代码如下:

NSString *jsString = [NSString stringWithFormat:@"<html> \n"

"<head> \n"

"<style type=\"text/css\"> \n"

"body {font-size: %f; font-family: \"%@\"; color: %@;}\n"

"</style> \n"

"</head> \n"

"<body>%@</body> \n"

"</html>", fontSize, fontFamily, fontColor, htmlText];

[_infoTextView loadHTMLString:jsString baseURL:nil];

另外也可以通过加载本地的css文件,将格式在css文件中定义,代码如下:

NSString *jsString = [NSString stringWithFormat:@"<html> \n"

"<head> \n"

"<link href=\"text.css\" rel=\"stylesheet\" type=\"text/css\"> \n"

"</style> \n"

"</head> \n"

"<body>%@</body> \n"

"</html>", tempText];

NSString *path = [[NSBundle mainBundle] bundlePath];

NSURL *baseURL = [NSURL fileURLWithPath:path];

[infoWebView loadHTMLString:jsString baseURL:baseURL];

2、计算UIWebView的高度

网上有文章介绍使用如下代码计算高度,但用过后感觉不准确,主要是因为有时候html还没加载完计算就不准确了。

CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

后来使用如下方法比较准确,就是加载完成后再去计算,不过有个问题是,第一次计算出来高度同时设置了对应高度后,后面计算的结果会受第一次的结果影响,也 就是说高度保持第一次计算的结果。我测试的是第一次是内容较多,后面几次是内容较少,但是高度始终保持第一次的高度,不知如果后面的内容比第一次的多,会 不会重新计算还是保持第一次的计算结果。所以保险一点,在每次计算之前,先重设一下高度。

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

const CGFloat defaultWebViewHeight = 22.0;

//reset webview size

CGRect originalFrame = webView.frame;

webView.frame = CGRectMake(originalFrame.origin.x, originalFrame.origin.y, 320, defaultWebViewHeight);

CGSize actualSize = [webView sizeThatFits:CGSizeZero];

if (actualSize.height <= defaultWebViewHeight) {

actualSize.height = defaultWebViewHeight;

}

CGRect webViewFrame = webView.frame;

webViewFrame.size.height = actualSize.height;

webView.frame = webViewFrame;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: