UIWebView用得比较少,所以经常碰到相同的问题会忘记,要翻箱倒柜找回旧代码,现将常用的一些属性或者用法记录下来,方便自己和有需要的人查看。
1、UIWebView设置字体大小,颜色,字体:
UIWebView无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置,代码如下:
UIWebView用得比较少,所以经常碰到相同的问题会忘记,要翻箱倒柜找回旧代码,现将常用的一些属性或者设置记录下来,方便自己和有需要的人查看。
1、UIWebView设置字体大小,颜色,字体:1、UIWebView设置字体大小,颜色,字体:
UIWebView无法通过自身的属性设置字体的一些属性,只能通过html代码进行设置,代码如下: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; }